【发布时间】:2016-01-18 09:42:08
【问题描述】:
Android-
我收到以下 JSON 响应。当我点击特定 ID(1,1015,1016 见下文)时,我有按钮。它将返回内部 Json 对象。
我只有在获取特定 Ids(Json) 时遇到问题
[
{
"1":
[
{
"a": "a",
"b": 1,
"c": "1",
"d": "1-1-1-1"
},
{
"a": "a",
"b": 6,
"c": "2",
"d": "1-1-1",
"e": "Meals"
}
]
},
{
"1015":
[
]
},
{
"1016":
[
{
"a": "a",
"b": 6,
"c": "2",
"d": "1-1-1",
"e": "Meals1234"
}
]
},
{
"1012":
[
{
"a": "venky",
"b": 6,
"c": "2",
"d": "1-1-1",
"e": "Meals"
},
{
"a": "venky2",
"b": 45,
"c": "2",
"d": "1-1-1",
"e": "Meals"
}
]
},
{
"1011":
[
{
"a": "a",
"b": 6,
"c": "2",
"d": "1-1-1",
"e": "Meals567"
},
{
"a": "a",
"b": 6,
"c": "2",
"d": "1-1-1",
"e": "Meals08676"
}
]
}
]
我编写了用于 JSON 解析的 Java 代码如下
public void load_whole_JsonData() {
String number = ET_number.getText().toString().trim(); // edittext number is 1 (for example)
JSONArray jsonArray1;
JSONObject obj1;
JSONArray jsonArray2;
try {
jsonArray1=new JSONArray(JsonResponse); // parse the Json response here
obj1=new JSONObject();
for (int i = 0; i < jsonArray1.length(); i++) {
try {
jsonArray2= jsonArray1.getJSONObject(i).getJSONArray(number); //number is IDs : 1 , 1015,1016
Log.v("test", "i"+i+ " obj1 "+jsonArray2);
}
catch (Exception e){
Log.v("test", "exception "+e);
}
}
} catch (JSONException e) {
Log.v("MTV", "JsonParser exception" + e);
e.printStackTrace();
}
}
我得到了正确的输出,但 Catch 抛出,因为
jsonArray2 = jsonArray1.getJSONObject(i).getJSONArray(number); //number is IDs : 1 , 1015,1016
输出(在 Logcat 中):
V/test: i0 obj1 [{"a":"a","b":1,"c":"1","d":"1-1-1-1","e":"Meals"},{"a":"a","b":6,"c":"2","d":"1-1-1","e":"Meals"}] //This is the output
V/test: exception org.json.JSONException: No value for 1 //catch exceptions
V/test: exception org.json.JSONException: No value for 1
V/test: exception org.json.JSONException: No value for 1
V/test: exception org.json.JSONException: No value for 1
如果有人想在不捕获异常的情况下获得输出。 那么如何获取内部详细信息,例如[{"a":"a","b":1,"c":"1","d":"1-1-1-1","e":"Meals"},{"a":"a","b":6,"c":"2","d":"1-1-1","e":"Meals"}]
已编辑:
如果我给出的数字是 1016。它只会解析 1016 的内部细节 [{"a":"a","b":1,"c":"1","d":"1 -1-1-1","e":"Meals"}(从整个 JSON 响应中获取)
【问题讨论】:
-
您有两个变量
number具有相同的类型String。你确定你的代码正在编译吗? -
您问题中的第一个正确代码。一旦你写了
jsonArray2= jsonArray1.getJSONObject(i).getJSONArray(number);,在另一个地方你写了obj2 = jsonArray1.getJSONObject(i).getJSONArray(number);。如果您在发布前编辑代码,请正确操作。 -
我只是给出了考虑的数字(字符串编号=1)。现在我删除了@Rohit5k2
-
谢谢。我更正了我的 Code@Rohit5k2
-
我已经在我的回答中更正了这个问题。请尝试一下。