我有一个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);
}
}
}
问题是,当我们在personalInfo中有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
我希望同时显示两个地址的数据。
最佳答案
这应该可以解决您的问题
public static void printJsonObject(JSONObject jsonObj) {
for (Object key : jsonObj.keySet()) {
String keyStr = (String) key;
Object keyvalue = jsonObj.get(keyStr);
if (keyvalue instanceof JSONObject) {
printJsonObject((JSONObject) keyvalue);
} else if (keyvalue instanceof JSONArray) {
JSONArray array = (JSONArray) keyvalue;
for (int i = 0; i < array.length(); i++) {
printJsonObject((JSONObject) array.get(i));
}
} else {
System.out.println(keyStr + ", " + keyvalue);
}
}
}