【发布时间】:2018-03-18 10:17:14
【问题描述】:
我一直在尝试从我的 JSON 中提取数组元素,但目前无法做到。
我有以下 JSON:
{
"Sample JSON": [{
"Title": "Title1",
"Audit": [{
"auditId": "01",
"type": "sampleType",
"auditText": "sampleText",
"answer": ["Ans1", "Ans2"]
},
{
"auditId": "02",
"type": "sampleType2",
"auditText": "sampleText2",
"answer": ["Ans1", "Ans2", "Ans3", "Ans4"]
}
]
},
{
"Title": "Title2",
"Audit": [{
"auditId": "03",
"type": "sampleType3",
"auditText": "sampleText3",
"answer": ["Ans1", "Ans2"]
},
{
"auditId": "04",
"type": "sampleType4",
"auditText": "sampleText4",
"answer": ["Ans1", "Ans2", "Ans3", "Ans4"]
}
]
}
]
}
我想提取数组'answer'的数组元素。
我在以下方法的注释中指出的行中出现异常:
public void getAudit(String myJSON) {
auditList = new ArrayList<AuditList>();
String title;
String auditId;
String type;
String auditText;
ArrayList<String> answer = new ArrayList<>();
try {
JSONObject jsonObj = new JSONObject(myJSON);
JSONArray jssArray = jsonObj.getJSONArray("Sample JSON");
int jsonArrLength = jssArray.length();
for (int i = 0; i < jsonArrLength; i++) {
JSONObject jsonChildObj = jssArray.getJSONObject(i);
title = jsonChildObj.getString("Title");
JSONArray jssArray1 = jsonChildObj.getJSONArray("Audit");
for (int i1 = 0; i1 < jssArray1.length(); i1++) {
JSONObject jsonChildObj1 = jssArray1.getJSONObject(i1);
type = jsonChildObj1.optString("type");
auditText = jsonChildObj1.optString("auditText");
auditId = jsonChildObj1.optString("auditId");
JSONArray jssArray2 = jsonChildObj1.getJSONArray("answer");
//Getting exception in above line
for (int j=0; j<jssArray2.length(); j++)
{
answer.add(jssArray2.get(j).toString()) ;
}
AuditList aList = new AuditList();
aList.setQuesId(auditId);
aList.setQuesText(auditText);
aList.setQuesTypw(auditType);
aList.setAnswer(answer);
aList.setCategoryName(title);
auditList.add(aList);
}
}
.
.
.
.
.
}
我使用调试器在上面指出的行中发现了异常。 找不到提取数组“答案”的数组元素的方法。 请帮忙。
【问题讨论】:
-
哪一行??请分享你的logcat
-
我在上面的方法中作为注释提到了它: JSONArray jssArray2 = jsonChildObj1.getJSONArray("answer"); //在上面的行中获取异常
-
异常信息是什么?类型、auditId、auditText 怎么样 - 你是否正确获取了这些值?
-
@lorraine:异常消息是:“org.json.JSONException:java.lang.String 类型的答案值无法转换为 JSONArray”。抱歉回复晚了。