Search code examples
javaarraysjsonobjectmapper

What is the best way to extract a value without having a Java Object class


I have a string like below

{
    "id": "abc",
    "title": "123.png",
    "description": "fruits",
    "information": [
        {
            "type": "apple",
            "url": "https://apple.com"
        },
        {
            "type": "orange",
            "url": "https://orange.com"
        }
    ],
    "versions": 0
}

I want to get the value of url where type: orange. The list in information may not always be in same order as appearing in the data above. I know I could do it easily in python with json.loads and json.dump.

I am trying to do it java using JsonNode and objectMapper.readTree.at("/information") but I am unable to get past this point in a clever neat way to get the list and fetch the url where type = orange.


Solution

  • This is pretty straightforward

    Use a JSON library and parse the response using the library. Then get only the values and attributes that you need...

    Example relevant to your case:

    // Get your Json and transform it into a JSONObject
    
    JSONObject mainObject = new JSONObject(yourJsonString); // Here is your JSON...
    
    // Get your "information" array
    
    JSONArray infoArray = mainObject.getJSONArray("information"); // Here you have the array
    
    // Now you can go through each item of the array till you find the one you need
    
    for(int i = 0 ; i < infoArray.length(); i++)
    {
        JSONObject item = participantsArray.getJSONObject(i);
    
        final String type = item.getString("type");
        final String url = item.getString("url");
    
        if(type.equals("orange"))
        {
            // DO WHATEVER YOU NEED
        }
    }