gpt4 book ai didi

java - 解析 JSON 字符串时出现问题

转载 作者:行者123 更新时间:2023-11-29 07:48:32 25 4
gpt4 key购买 nike

我的 json 字符串看起来像,

{
"userList" : {
"user" : [{
"Id" : "33",
"userId" : "raji2",
"customerId" : "35",
"username" : "raji2",
"status" : "1",
"locked" : "0",
"customAttributes" : "{\"uiPageId\":\"\",\"uiPageName\":\"\",\"uiPageViewMode\":\"Normal\"}",
"addressList" : {
"address" : ""
},
"contactList" : {
"contact" : {
"contactno" : "+919526346097",
"email" : "raji@gmail.com"
}
},
"roleList" : {
"roleId" : "7"
},
"privilegeList" : {
"privilegeId" : ["1", "10", "11", "12", "13", "14", "15", "16", "17", "23", "24", "25", "26", "27"]
},
"entityList" : {
"entityId" : ""
}
}, {
"Id" : "34",
"userId" : "raji3",
"customerId" : "35",
"username" : "raji3",
"status" : "1",
"locked" : "0",
"customAttributes" : "{\"uiPageId\":\"\",\"uiPageName\":\"\",\"uiPageViewMode\":\"Normal\"}",
"addressList" : {
"address" : ""
},
"contactList" : {
"contact" : {
"contactno" : "+919526346097",
"email" : "raji@gmail.com"
}
},
"roleList" : {
"roleId" : "7"
},
"privilegeList" : {
"privilegeId" : ["1", "10", "11", "12", "13", "14", "15", "16", "17", "23", "24", "25", "26", "27"]
},
"entityList" : {
"entityId" : ""
}
}
]
}
}

当我尝试使用下面给出的示例解析它并尝试获取电子邮件或 customerId 时,数据为空,我尝试的代码片段是:

    JSONObject obj = (JSONObject) new JSONParser().parse(data);
JSONObject jsonObject = (JSONObject) obj;
System.out.println(jsonObject);
String x=(String) jsonObject.get("customerId");
System.out.println("Check Data"+x);

我使用了简单的 json 库。我收到空响应。

最佳答案

正如其他评论者所说,您不能直接从根元素访问“customerId”。你得走了

root -> userList -> user -> user[0] -> customerId

下面的代码实现了这个

JSONObject obj = (JSONObject) new JSONParser().parse(data);
System.out.println(obj);
JSONObject userList = (JSONObject) obj.get("userList");
JSONArray user = (JSONArray) userList.get("user");
JSONObject userObj = (JSONObject) user.get(0);
String customerId = (String) userObj.get("customerId");
System.out.println("Check Data " + customerId);

因为每个用户对象都有一个 customerId 属性,所以您必须选择要使用的用户对象。如果您希望使用第二个用户对象,您可以将 user.get(1); 放在第五行。

编辑 要获取每个用户的 customerId,请将最后三行替换为循环:

JSONObject obj = (JSONObject) new JSONParser().parse(data);
System.out.println(obj);
JSONObject userList = (JSONObject) obj.get("userList");
JSONArray user = (JSONArray) userList.get("user");
for (Object userObj : user) {
JSONObject userJSONObject = (JSONObject) userObj;
String customerId = (String) userJSONObject.get("customerId");
System.out.println("Check Data " + customerId);
}

关于java - 解析 JSON 字符串时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23309710/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com