我刚开始用java解析JSON。我有一个JSON字符串:
[
{
"projectId":5,
"userName":"clinician",
"projectName":"r",
"projectSummary":"r",
"projectLanguage":"r",
"contactPersonName":"r",
"contactPersonCV":"r",
"contactPersonEmail":"r",
"contactPersonPhone":"r"
},
[
{
"consentFileId":2,
"projectId":5,
"consentDescription":"r",
"consentFileName":"test.pdf",
"servicePathToGetConsentPdf":null
},
{
"consentFileId":3,
"projectId":5,
"consentDescription":"rrr",
"consentFileName":"test.pdf",
"servicePathToGetConsentPdf":"localhost:8080/4c_viewFile?consentFileId=3"
}
],
[
{
"anonymized_patient_identifier":"r",
"projectId":5
},
{
"anonymized_patient_identifier":"2",
"projectId":5
},
{
"anonymized_patient_identifier":"5",
"projectId":5
}
]]
我成功地从更简单的JSON字符串中获得了值,但是这个字符串有多个级别,而且每个级别都没有键。我尝试使用这样简单的代码:
Object obj = parser.parse(data);
JSONObject jsonObject = (JSONObject) obj;
resultJson = (String) jsonObject.get("projectId");
resultJson += "\n";
resultJson += (String) jsonObject.get("userName");但是我得到了错误java.lang.ClassCastException:不能将org.json.simple.JSONArray转换为org.json.simple.JSONObject,而且我也不知道如何在没有键的情况下获得较低级别的值。我也试图将它保存为一个JSONArray,但是它没有工作。
发布于 2015-05-12 13:12:50
json的根是JSONArray类型,根数组中存储的第一个对象是一个对象,您可以使用index = 0检索它。
这是一种让您的代码工作的黑客:
JSONArray jsonArray = JSONArray.fromObject(data);
JSONObject jsonObject=obj.getJSONObject(0);
resultJson = (String) jsonObject.get("projectId");
resultJson += "\n";
resultJson += (String) jsonObject.get("userName");注意:
若要将字符串转换为JSONArray,可以执行以下操作:
JSONArray array = JSONArray.fromObject(data);发布于 2015-05-12 13:16:36
为了改进nafas的答案,我会这样做来查看数组中的所有对象:
Object obj = parser.parse(data);
JSONArray jsonArray = (JSONArray) obj;
for (int i = 0; i < jsonArray.size (); i++) {
JSONObject jsonObject=obj.getJSONObject(i);
resultJson = (String) jsonObject.get("projectId");
resultJson += "\n";
resultJson += (String) jsonObject.get("userName");
}https://stackoverflow.com/questions/30191860
复制相似问题