解析 JSON 在 Android ,不获取值

发布时间: 2016/10/10 21:37:56
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

能够分析需要除了target_id 的 field_exercis_arc中的一切 !
我得到的 nid、 标题和正文。不知道如何获取 id 的 field_exercis_arc。


JSON

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

代码

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);
            }

Field_exercis_arc 和 target_id 的领域模型

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;
    }
}

在此先感谢

解决方法 1:

使用以下代码︰

exercis.setTarget_id(finalObject.getJSONArray("field_exercis_arc").getString(j));
赞助商