Skip to content
Advertisement

Get json object in Array based on key and value in Java

I have a Json body like the example below. I need to extract the value from a key that has another key with a specific value in an array. I am passing in a JsonNode with everything in the detail component of the message, I can easily extract from each level, however, I’m struggling with the array.

In this case, I need to extract the value of “value” (Police/Fire/Accident Report) from the object in the array which has a key/value pair of “name”:”documentTitle”. I understand this is a JSONArray, but I can’t find a good example that shows me how to extract the values for an object in the array that contains a certain key/value pair, I don’t think I can rely on getting the object in position [2] in the array as the same objects may not always be present in the additionalMetadata array.

Sample Json:

    "sourceVersion": "1.0",
    "eventId": "8d74b892-810a-47c3-882b-6e641fd509eb",
    "clientRequestId": "b84f3a7b-03cc-4848-a1e8-3519106c6fcb",
    "detail": {
        "stack": "corona",
        "visibilityIndicator": null,
        "documentUid": "b84f3a7b-03cc-4848-a1e8-3519106c6fcb",
        "additionalMetadata": [
            {
                "name": "lastModifiedDate",
                "value": "2021-05-21T04:53:53Z"
            },
            {
                "name": "documentName",
                "value": "Police/Fire Report, 23850413, 2021-05-20 14:51:23"
            },
            {
                "name": "documentTitle",
                "value": "Police/Fire/Accident Report"
            },
            {
                "name": "documentAuthor",
                "value": "System Generated"
            },
            {
                "name": "lastModifiedBy",
                "value": "System Updated"
            },
            {
                "name": "createdBy",
                "value": "System Generated"
            },
            {
                "name": "documentDescription",
                "value": "Police/Fire Report received"
            },
            {
                "name": "organizationCode",
                "value": "Claims"
            }
        ]
    }
}```

Advertisement

Answer

Loop through the json array and extract the json object with name documentTitile. From that json object you can get the value

1 People found this is helpful
Advertisement