首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Java中解析没有键的JSON字符串

在Java中解析没有键的JSON字符串
EN

Stack Overflow用户
提问于 2015-05-12 13:07:35
回答 2查看 3.4K关注 0票数 0

我刚开始用java解析JSON。我有一个JSON字符串:

代码语言:javascript
复制
[
{
    "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字符串中获得了值,但是这个字符串有多个级别,而且每个级别都没有键。我尝试使用这样简单的代码:

代码语言:javascript
复制
     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,但是它没有工作。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-05-12 13:12:50

json的根是JSONArray类型,根数组中存储的第一个对象是一个对象,您可以使用index = 0检索它。

这是一种让您的代码工作的黑客:

代码语言:javascript
复制
 JSONArray jsonArray = JSONArray.fromObject(data);
 JSONObject jsonObject=obj.getJSONObject(0);
 resultJson = (String) jsonObject.get("projectId");
 resultJson += "\n";
 resultJson += (String) jsonObject.get("userName");

注意:

若要将字符串转换为JSONArray,可以执行以下操作:

代码语言:javascript
复制
JSONArray array = JSONArray.fromObject(data);
票数 4
EN

Stack Overflow用户

发布于 2015-05-12 13:16:36

为了改进nafas的答案,我会这样做来查看数组中的所有对象:

代码语言:javascript
复制
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");
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30191860

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档