Hi I have a nested JSON which has JSON array also. i need all single key-value pairs. below is the nested JSON which has some JSON arrays.
{
"relatedquoteresponse":{
"responsepreamble":{
"responseStatus":"Passed",
"statusCode":"200"
},
"phone":null,
"symbol":"$",
"retrieverelatedquotes":[
{
"quoteId":23232
},
{
"quoteName":"Netally-Service"
}
],
"CheckStatus":{
"StatusCode":200,
"responseMessage":"Found"
}
}
}
I need an output like this:
responseStatus : "Passed"
statusCode : "200"
Phone: null
symbol: "$"
quoteID: 23232
quoteName: "Netally-Service"
I tried below code, but getting this output.
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(json);
Iterator<String> iterator = jsonNode.fieldNames();
while (iterator.hasNext()) {
String key = iterator.next();
printRec(jsonNode, key);
}
public static void printRec(JsonNode jsonNode, String key) {
JsonNode node = jsonNode.get(key);
if (node.isObject()) {
Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
fields.forEachRemaining(field -> {
printRec(node, field.getKey());
if (!field.getValue().isObject()) {
System.out.println(field.getKey() + " : " + field.getValue());
}
});
}
}
OutPut:
responseStatus : "Passed"
statusCode : "200"
Phone: null
symbol: "$"
retrieverelatedquotes : [{"quoteId":23232},{"quoteName":"Netally-Service"}]
Can anyone help me on this to get all key-value pairs not in array like above.
Thanks
Recursion really helps, even works for multiple levels.
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(json);
printRec(jsonNode, "");
----------
public static void printRec(String key, JsonNode jsonNode) {
if (jsonNode.isValueNode()) {
System.out.println(key + " : " + jsonNode);
} else if (jsonNode.isObject()) {
jsonNode.fields().forEachRemaining(field -> printRec(field.getKey(), field.getValue()));
} else if (jsonNode.isArray()) {
for (int i = 0; i < jsonNode.size(); i++) {
printRec(key + "[" + i + "]", jsonNode.get(i));
}
}
}
Output
responseStatus : "Passed"
statusCode : "200"
phone : null
symbol : "$"
quoteId : 23232
quoteName : "Netally-Service"
StatusCode : 200
responseMessage : "Found"