Home > OS >  Get all key-value pair from nested JSON array
Get all key-value pair from nested JSON array

Time:08-31

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

CodePudding user response:

Question is not really clear. So if you get a real array how you plan to manage it? Anyway the simpliest way is to create POJO object for mapping and map JSON to this object.

CodePudding user response:

You can use Regex named groups feature to get all single keys and values

Pattern pattern = Pattern.compile("\"(. )\":(?![{\\[])(. )");
Matcher matcher = pattern.matcher(content);
while (matcher.find()) {
    System.out.println(matcher.group(1)   " : "   matcher.group(2));
}

Output will be:

responseStatus : "Passed",
statusCode : "200"
phone : null,
symbol : "$",
quoteId : 23232
quoteName : "Netally-Service"
StatusCode : 200,
responseMessage : "Found"

You can easily modify the pattern to get all single keys with int value for example or null value

Simple article about Regex Named groups and Backreferences

  • Related