gpt4 book ai didi

java - 来自 JSON 文件的 Java 中的键值对

转载 作者:行者123 更新时间:2023-12-02 11:07:49 25 4
gpt4 key购买 nike

我有一个 JSON 数据

{
"HiServiceInquiryResponse": {
"CoverageInfoResponse": {
"Participant": {
"ns1:PersonalInfo": {
"ns1:LastName": "AA",
"ns1:Address": [
{
"ns1:Province": "",
"ns1:State": "CA",
"ns1:City": "LOS ANGELES",
"ns1:Country": "US",
"ns1:Address2": "",
"ns1:Address1": "test",
"ns1:PostalCode": 12345
},
{
"ns1:Province": "",
"ns1:State": "CA",
"ns1:City": "LOS ANGELES",
"ns1:Country": "US",
"ns1:Address2": "",
"ns1:Address1": "test",
"ns1:PostalCode": 12345
}
],
"ns1:FirstName": "BB"
},
"ns1:Coverage": "",
"ns1:HiClientId": 57,
"ns1:Employment": {
"ns1:EmployeeId": 1234,
"ns1:TaxId": 111
}
}
}
}

}

我想读取所有键值对并存储它们。到目前为止我能做到

    public static void printJsonObject(JSONObject jsonObj) {

for (Object key : jsonObj.keySet()) {
String keyStr = (String) key;
Object keyvalue = jsonObj.get(keyStr);

if (!(keyvalue instanceof JSONObject)) {
System.out.println(keyStr + ", " + keyvalue);
}
if (keyvalue instanceof JSONObject) {
printJsonObject((JSONObject) keyvalue);
}
}
}

问题是当我们的个人信息中有 2 个地址时,它不会单独读取它们。

当只有 1 个地址时我的输出:->

    ns1:LastName, AA
ns1:Province,
ns1:State, CA
ns1:City, LOS ANGELES
ns1:Country, US
ns1:Address2,
ns1:Address1, test
ns1:PostalCode, 12345
ns1:FirstName, BB
ns1:Coverage,
ns1:HiClientId, 57
ns1:EmployeeId, 1234
ns1:TaxId, 111

当有 2 个地址时我的输出:->

    ns1:LastName, AA
ns1:Address, [{"ns1:Province":"","ns1:State":"CA","ns1:City":"LOS ANGELES","ns1:Country":"US","ns1:Address2":"","ns1:Address1":"test","ns1:PostalCode":12345},{"ns1:Province":"","ns1:State":"CA","ns1:City":"LOS ANGELES","ns1:Country":"US","ns1:Address2":"","ns1:Address1":"test","ns1:PostalCode":12345}]
ns1:FirstName, BB
ns1:Coverage,
ns1:HiClientId, 57
ns1:EmployeeId, 1234
ns1:TaxId, 111

我希望显示两个地址的数据。

最佳答案

要解析 JSONObject 内的数组,您必须检查 JSONArray 的值实例,并为每个数组项递归调用 printJsonObject:

public static void printJsonObject(JSONObject jsonObj) {
for (Object key : jsonObj.keySet()) {
Object value = jsonObj.get(key);

if (value instanceof JSONObject)
printJsonObject((JSONObject)value);
else if (value instanceof JSONArray)
((JSONArray)value).forEach(obj -> printJsonObject((JSONObject)obj));
else
System.out.println(key + ", " + value);
}
}

关于java - 来自 JSON 文件的 Java 中的键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50824607/

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