Charm Geld Charm Geld - 2 months ago 6
JSON Question

Parsing JSON in Android, not getting value

I am able to parse everything i need, except for the target_id's in the field_exercis_arc.
I get the nid, title and body. Not sure how to get the id's in the field_exercis_arc.


The JSON


[{
"nid": "26",
"title": "Question test",
"body": "xcvxcv",
"field_exercis_arc": ["25","27"]
}]


The Code

String finalJson = buffer.toString();
JSONArray parentArray = new JSONArray(finalJson);
List<ExerciseModel> exerciseModelList = new ArrayList<>();

for(int i=0; i<parentArray.length(); i++){
JSONObject finalObject = parentArray.getJSONObject(i);

title_exi = finalObject.getString("title");
text_exi = finalObject.getString("body");
//This part is working.
ExerciseModel exerciseModel = new ExerciseModel();
exerciseModel.setTitle(finalObject.getString("title"));
exerciseModel.setNid(finalObject.getInt("nid"));
exerciseModel.setBody(finalObject.getString("body"));

//Problem with this part, not getting the target_id's.
List<ExerciseModel.Exer> exerList = new ArrayList<>();
for(int j=0; j<finalObject.getJSONArray("field_exercis_arc").length(); j++){
ExerciseModel.Exer exercis = new ExerciseModel.Exer();
exercis.setTarget_id(finalObject.getJSONArray("field_exercis_arc").getJSONObject(j).getString("target_id"));
exerList.add(exercis);
}
exerciseModel.setExerList(exerList);
exerciseModelList.add(exerciseModel);

mDB.saveRecordEX(exerciseModel);
}


The model for the field_exercis_arc and target_id's fields

private List<Exer> exerList;
public List<Exer> getExerList() {
return exerList;
}

public void setExerList(List<Exer> exerList) {
this.exerList = exerList;
}

public static class Exer{
private String target_id;
public String getTarget_id() {
return target_id;
}
public void setTarget_id(String target_id) {
this.target_id = target_id;
}
}


Thanks in advance

Answer

Use below code :

exercis.setTarget_id(finalObject.getJSONArray("field_exercis_arc").getString(j));
Comments