我正在尝试解析一个齐射json响应,其中第一个数组Sub1在尝试解析第二个Sub2时工作正常,Sub2返回异常而没有Sub2的值。
[{
"Id": 1,
"Title1": "Title1",
"Title2": "title2",
"Title3": "title3",
"Link1": "link",
"Link2": "link",
"Link3": "link",
"Ord": 1,
"Sub1": [{
"Id": 58,
"Title1": "Title1",
"Title2": "Title2",
"Title3": "Title3",
"Link1": "link",
"Link2": "link",
"Link3": "link",
"Ord": 1,
"Sub2": [{
"Id": 69,
"Title1": "Title1",
"Title2": "Title2",
"Title3": "Title3",
"Link1": "link",
"Link2": "link",
"Link3": "link",
"Ord": 1
}]
}]
}]
这是代码的解析部分:
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
id = person.getString("Id");
titleel = person.getString("Title1");
linkel = person.getString("Link1");
ordinal = person.getString("Ord");
JSONArray sub = person.getJSONArray("Sub1");
for(int j =0; j<sub.length(); j++){
JSONObject subobj = sub.getJSONObject(j);
subtitle = subobj.getString("Title1");
subtitleen = subobj.getString("Title2");
subtitlede = subobj.getString("Title3");
subid = subobj.getString("Id");
sublinkel = subobj.getString("Link1");
sublinken = subobj.getString("Link2");
sublinkde = subobj.getString("Link3");
subordinal =subobj.getString("Ord");
JSONArray suba = subobj.getJSONArray("Sub2");
for(int k =0; k<suba.length(); k++) {
JSONObject subobja = suba.getJSONObject(k);
subtitlea = subobja.getString("Title1");
subtitleena = subobja.getString("Title2");
subtitledea = subobja.getString("Title3");
subida = subobja.getString("Id");
sublinkela = subobja.getString("Link1");
sublinkena = subobja.getString("Link2");
sublinkdea = subobja.getString("Link3");
subordinala = subobja.getString("Ord");
}
}
}
答案 0 :(得分:0)
好了,经过两天的搜索,我终于找到了问题所在。 就像Raghunandan说我替换了每个get方法的选择。
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
id = person.optString("Id");
titleel = person.optString("Title1");
linkel = person.optString("Link1");
ordinal = person.optString("Ord");
JSONArray sub = person.optJSONArray("Sub1");
for(int j =0; j<sub.length(); j++){
JSONObject subobj = sub.optJSONObject(j);
subtitle = subobj.optString("Title1");
subtitleen = subobj.optString("Title2");
subtitlede = subobj.optString("Title3");
subid = subobj.optString("Id");
sublinkel = subobj.optString("Link1");
sublinken = subobj.optString("Link2");
sublinkde = subobj.optString("Link3");
subordinal =subobj.optString("Ord");
JSONArray suba = subobj.optJSONArray("Sub2");
for(int k =0; k<suba.length(); k++) {
JSONObject subobja = suba.optJSONObject(k);
subtitlea = subobja.optString("Title1");
subtitleena = subobja.optString("Title2");
subtitledea = subobja.optString("Title3");
subida = subobja.optString("Id");
sublinkela = subobja.optString("Link1");
sublinkena = subobja.optString("Link2");
sublinkdea = subobja.optString("Link3");
subordinala = subobja.optString("Ord");
}
}
}