我正在尝试解析以下json,但由于出现堆栈溢出错误而无法做到这一点。
这是JSON-
[{
"Class": "1",
"school": "test",
"description": "test",
"student": [
"Student1",
"Student2"
],
"qualify": true,
"annualFee": 3.00
}]
Run Code Online (Sandbox Code Playgroud)
这是当前失败的代码。
String res = cspResponse.prettyPrint();
org.json.JSONObject obj = new org.json.JSONObject(res);
org.json.JSONArray arr = obj.getJSONArray(arrayName);
String dataStatus=null;
for (int i = 0; i < arr.length(); i++) {
dataStatus = arr.getJSONObject(i).getString(key);
System.out.println("dataStatus is \t" + dataStatus);
}
Run Code Online (Sandbox Code Playgroud)
用例是:
我感谢您的帮助。
update-1 使用以下详细信息更新有关堆栈跟踪的更多信息。cls = 1
错误- org.json.JSONException: JSONObject["student "] not a string.
堆栈跟踪-
public String getString(String key) throws JSONException {
Object object = this.get(key);
if (object instanceof String) {
return (String) object;
}
throw new JSONException("JSONObject[" + quote(key) + "] not a string.");
}
Run Code Online (Sandbox Code Playgroud)
当我使用以下答案运行代码时,此处对学生而言失败的不是字符串。
我从前两个注释中使用的答案都具有相同的错误。我请你帮忙。
您的json片段无效-最后一个逗号中断了解析。但是其余的代码是相当可行的。
String res = "[\n" +
" {\n" +
" \"Class\": \"1\",\n" +
" \"school\": \"test\",\n" +
" \"description\": \"test\",\n" +
" \"student\": [\n" +
" \"Student1\",\n" +
" \"Student2\"\n" +
" ],\n" +
" \"qualify\": true,\n" +
" \"annualFee\": 3.00\n" +
" }\n" +
"]";
JSONArray arr = new JSONArray(res);
for (int i = 0; i < arr.length(); i++) {
JSONObject block = arr.getJSONObject(i);
Integer cls = block.getInt("Class");
System.out.println("cls = " + cls);
Object school = block.getString("school");
System.out.println("school = " + school);
JSONArray students = block.getJSONArray("student");
System.out.println("student[0] = " + students.get(0));
System.out.println("student[1] = " + students.get(1));
}
Run Code Online (Sandbox Code Playgroud)
应该输出
cls = 1
school = test
student[0] = Student1
student[1] = Student2
Run Code Online (Sandbox Code Playgroud)