How can I loop through this kind of JSON array?
[
{
"full_name": "Abc Xyz"
},
{
"full_name": "Def Xyz"
},
{
"full_name": "Nml Xyz"
},
{
"full_name": "Jol Xyz"
}
]
Thank you!
try this
try {
JSONArray a = new JSONArray(myjsonString);
for(int i = 0; i < a.length(); i++)
{
JSONObject o = a.getJSONObject(i);
String name = o.getString("full_name");
}
} catch (JSONException e) {
e.printStackTrace();
}
Your jsonString contains array of objects so here is code:
try {
// [] indicates array so top element is array
JSONArray jsonArray = new JSONArray(jsonString);
for(int i = 0; i < jsonArray.length(); i++)
{
// {} indicates object so array elements are objects
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.getString("full_name");
}
} catch (JSONException e) {
e.printStackTrace();
}
Updated : Google GSON
Also try Google's GSON this is excellent library to handle jsons you can serialize and deserialize the json and class objects.
checkout this link: Google Gson
Try
try {
JSONArray array = new JSONArray(jsonString);
for(int i = 0; i < array.length(); i++) {
JSONObject json = array.getJSONObject(i);
String fullName = json.getString("full_name");
}
} catch (JSONException e) {
e.printStackTrace();
}
Related
I have a JSONArray and when I try to parse it, an NPE shows and the logcat shows W/System.err: org.json.JSONException: Value at 0 is null. Please help. I have provided my codes below.
JSON Array
[
{
"student_number":"201411870",
"full_name":"Miranda , Andrew Matthew Matera",
"year":"4",
"course":"BSIT"
}
]
Code Snippet
ArrayList<User> userArrayList = new JsonConverter<User>().toArrayList(response, User.class);
JSONArray jsonArray = new JSONArray(userArrayList);
try {
int regStudentNumber = jsonArray.getJSONObject(0).getInt("student_number");
String regFullName = jsonArray.getJSONObject(1).getString("full_name");
int regYear = jsonArray.getJSONObject(2).getInt("year");
String regCourse = jsonArray.getJSONObject(3).getString("course");
tvStudentNumber.setText(String.valueOf(regStudentNumber));
tvFullName.setText(regFullName);
tvYear.setText(String.valueOf(regYear));
tvCourse.setText(regCourse);
} catch (JSONException e) {
e.printStackTrace();
}
Solved it on my own. Sorry for the unclear question.
try {
JSONArray jsonArray = new JSONArray(response);
if(jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int regStudentNumber = jsonObject.getInt("student_number");
String regFullName = jsonObject.getString("full_name");
int regYear = jsonObject.getInt("year");
String regCourse = jsonObject.getString("course");
tvStudentNumber.setText(String.valueOf(regStudentNumber));
tvFullName.setText(regFullName);
tvYear.setText(String.valueOf(regYear));
tvCourse.setText(regCourse);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
First of all parse JSON array to object to make clear it is for a particular value then fetch things from it based on need.
To parse json array to object use code
try {
JSONArray jsonArray = new JSONArray(response);
if(jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I'm new to Android and I have tried so many options to access the JSONObject which returns from an API call but I couldn't succeed as any of the solutions i looked for didn't work for me.
What i want is to access the JSONObject and keep the Id & Name in a Array. And then populate the Names in a AutoCompleteTextView. How do i properly access the JSONObject. Please help me with this. I'm stuck on this for more than a day.
Following is my Code handling the JSONObject.
#Override
public void processFinish(JSONObject output) {
Toast.makeText(MainActivity.this,"ProcessFinish",Toast.LENGTH_SHORT).show();
allStations = output;
if(output != null){
Toast.makeText(MainActivity.this,output.toString(),Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this," Connection Failed!",Toast.LENGTH_SHORT).show();
}
}
Following is a sample output of my JSONObject
{
"SUCCESS": true,
"MESSAGE": "Found 398 Results!",
"NOFRESULTS": 3,
"RESULTS": {
"stationList": [
{
"stationCode": "ABN",
"stationID": 3,
"stationName": "ABLA"
},
{
"stationCode": "ADLA",
"stationID": 410,
"stationName": "ADLA"
},
{
"stationCode": "ANM",
"stationID": 11,
"stationName": "AHAMA"
}]
},
"STATUSCODE": "2000"
}
try this
try {
JSONObject obj= output.getJSONObject("RESULTS");
JSONArray dataArray= obj.getJSONArray(“stationList“);
for(int i=0;i<dataArray.length();i++)
{
JSONObject object1=dataArray.getJSONObject(i);
Strind id = object1.getString("stationID");
}
} catch (JSONException e) {
e.printStackTrace();
}
In This code output is your JSONObject result
try this
try {
JSONObject jsonObject = new JSONObject("response");
boolean status= jsonObject.getBoolean("SUCCESS");
String MESSAGE= jsonObject.getString("MESSAGE");
String NOFRESULTS= jsonObject.getString("NOFRESULTS");
String STATUSCODE= jsonObject.getString("STATUSCODE");
JSONObject obj=jsonObject.getJSONObject("RESULTS");
JSONArray jsonarray = obj.optJSONArray("stationList");
for (int i = 0; i < jsonarray.length(); i++){
JSONObject json_data = jsonarray.getJSONObject(i);
Log.e("stationCode",json_data.getString("stationCode"));
Log.e("stationID",json_data.getString("stationID"));
Log.e("stationName",json_data.getString("stationName"));
}
} catch (JSONException e) {
e.printStackTrace();
}
Have you tried using a JSON Array? For example you could use this method for storage:
JSONObject wgroup = new JSONObject(); //FINAL json object
try { //put initial data
wgroup.put("id", "2");
wgroup.put("user", "someone");
wgroup.put("stime", "2017-02-06 16:30:13");
wgroup.put("etime", "2017-02-06 19:30:13");
wgroup.put("real_dur", 3600);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray1 = new JSONArray(); //Create an array to store ALL Variables
for (int y=0; y< your_array.length ; y++ ){ //loop through your information array
JSONObject output = new JSONObject(); //CREATE a json object to put 1 workout
try {
wgroup.put("id", "2");
wgroup.put("name", "sam");
wgroup.put("age", "3");
wgroup.put("gender", "male");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray2 = new JSONArray(); //CREATE a json array to put 1 array
jsonArray1.put(output); //insert this OBJECT into the ARRAY
}
wgroup.put(jsonArray1);//insert the workouts ARRAY into the original object
How to read the images and its corresponding positions
"images": [
[
{
"images_url": "http://provenlogic.info/tinder_web/public/uploads/e9275d47cf5efd929794caafc50e957982c47582.jpg",
"position": "1"
},
{
"images_url": "http://provenlogic.info/tinder_web/public/uploads/c374561da8583a77b4d21ee4b06f30d1a3fac4bb.jpg",
"position": "3"
}
]
]
try {
JSONArray jsonArray = rootObject.getJSONArray("images");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String imageUrl=jsonObject.getString("images_url");
String position=jsonObject.getString("position");
}
} catch (Exception e) {
e.printStackTrace();
}
Happy Codding!!!
A JSON Object starts with a { and ends with a } while a JSON Array starts with a [ and ends with a ].
JSONArray jArray = json.getJSONArray("images").get;
for(int i = 0; i < jArray.length;i++)
{
JSONObject jObj = jsonArray.getJSONObject(i);
String imageUrl = jObj.getString("images_url");
String position = jObj.getString("position");
}
You will need to wrap the whole JSON Handling inside a try/catch block. You might want to try http://jsonlint.com/, an online json validator and https://jsonformatter.curiousconcept.com/, an online json formatter to understand easily!
Cheers!
First of all get the JsonArray by using array name "images"
and get each Json object .
try {
JSONArray jsonArray = new JSONArray("result");
for(int i=0;i<jsonArray.length();i++){
JSONArray jsonArray1=jsonArray.getJSONArray(i);
for(int j=0;j<jsonArray1.length();j++){
JSONObject jsonObject=jsonArray1.getJSONObject(j);
String imageurl=jsonObject.getString("images_url");
String position=jsonObject.getString("position");
}
}
}catch (Exception e){
e.printStackTrace();
}
I have this JSON String:
{
"Data": [
{
"id": "1",
"type": "formal",
"price": "999"
},
{
"id": "2",
"type": "sports",
"price": "799"
}
]
}
JAVA Code
try {
JSONObject parentObject = new JSONObject(result);
dataArray = parentObject.getJSONArray(TAG_ARRAY);
int i=0;
for(i=0;i < dataArray.length();i++) {
JSONObject finalObject = dataArray.getJSONObject(i);
price[i] = String.valueOf(finalObject.getInt(TAG_PRICE));
type[i] = finalObject.getString(TAG_TYPE);
}
} catch (JSONException e) {
e.printStackTrace();
}
I can't seem to be able to get data, is there something wrong?
Use this code. Here i used json-simple as JSON library.
JSONParser parser = new JSONParser();
try {
JSONObject jsonObject = (JSONObject) parser.parse(new FileReader("C:\\sample.json"));
String result = jsonObject.toString();
System.out.println(result);
JSONObject resJsonObject = (JSONObject) parser.parse(result);
JSONArray jsonArray = (JSONArray) jsonObject.get("Data");
for( int i =0; i<jsonArray.size(); i++){
JSONObject childJson = (JSONObject) jsonArray.get(i);
price[i] = (String) childJson.get("price");
type[i] = (String) childJson.get("type");
}
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(Arrays.toString(price));
System.out.println(Arrays.toString(type));
Use
try {
JSONObject parentObject = new JSONObject(result);
dataArray = parentObject.optJSONArray("Data");
int i=0;
for(i=0;i < dataArray.length();i++) {
JSONObject finalObject = dataArray.getJSONObject(i);
price[i] = String.valueOf(finalObject.getInt(TAG_PRICE));
type[i] = finalObject.getString(TAG_TYPE);
}
} catch (JSONException e) {
e.printStackTrace();
}
If you interract a lot with JSON, consider using gson or other dedicated json serialization libraries
How can i extract the json below and save it in an arraylist.
{
"trains": {
"train": [
{
"#id": 1000000103,
"#version": 1,
"#status": "active",
"#name": "dffffff",
"#description": "ffffff half of the nineteenth century.",
"#city": "fff",
"#phone": "+230 595-1454",
"#email": "ffffr#mffc.mu",
"#website": "www4u",
"#latitude": -5.2882,
"#longitude": 3.499,
"#defaultLocale": "",
"#holes": 48,
"#par": 72,
"#slope": 0,
"#distance": 5.005273,
"circuits": {
"circuit": []
},
"localizations": {
"localization": []
}
},
{
"#id": 1000000105,
"#version": 1,
"#status": "active",
"#name": " xClub",
"#description": "",
"#city": " xlet",
"#phone": "+44465\t",
"#email": "",
"#website": "wweffl.com",
"#latitude": -2.040318,
"#longitude": 54548,
"#defaultLocale": "",
"#holes": 18,
"#par": 32,
"#slope": 0,
"#distance": 2441673,
"circuits": {
"circuit": []
},
"localizations": {
"localization": []
}
}
]
}
}
my working
try {
jobj_trouve_train = new JSONObject(reponse_trouve_train);
String jsonobj = jobj_trouve_golf.getString("trains");
//String jsonobj1 = jobj_trouve_golf.getString("train");
//jobj_trouve_train = new JSONObject(reponse_trouve_train);
//jsonArray = jobj_trouve_golf.getJSONArray("trains");
//jsonArray= new JSONArray(jsonobj);
//System.out.println("jsonArray "+jsonArray);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Try this..
try {
jobj_trouve_train = new JSONObject(reponse_trouve_train);
JSONObject jsonobj = jobj_trouve_train.getJSONObject("trains");
JSONArray jsonobj1 = jsonobj.getJSONArray("train");
for(int i = 0;i< jsonobj1.length();i++){
JSONObject jsonj = jsonobj1.getJSONObject(i);
System.out.println("#id "+jsonj.getString("#id"));
// Same for remaining all
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You can use the Gson library developed by Google to parse Json into objects.
The reference is here:
https://code.google.com/p/google-gson/
And, a sample example is here:
JSON Parsing with GSON
JSONObject trains = jobj_trouve_train.getJSONObject("trains");
JSONArray trainArray = trains.getJSONArray("train");
JSONObject train1 = trainArray.getJSONObject(0);
...
if i didn't get confuse maybe this one will be right
JSONArray jasonArray = new JSONArray(result.getProperty("trains").toString());
for (int i = 0; i < jasonArray.length(); i++) {
JSONObject jsonObj = jasonArray.optJSONObject(i);
trainObject = new JSONObject(jsonObj.optString("train").toString());
int id = trainObject.optInt("id");
and so on..
}
public Object void toObject(String jsonMsg) throws JSONException {
JSONObject trains= (JSONObject) new JSONTokener(jsonMsg).nextValue();
if(trains.has("trains")){
JSONArray train = (JSONArray) new JSONTokener(object.getString("train")).nextValue();
for (int t = 0; t < jsonArray.length(); t++) {
String temp = jsonArray.getJSONObject(t).toString();
JSONObject object = (JSONObject) new JSONTokener(temp).nextValue();
if(object.has("#id"))
object.getString("#id");
// now similar procedure of reading
// read values and save it in an "object"
}
return savedObject;
}
-- tested, i have tried to modify code to match your JSON data. complete the rest.