Search code examples
jsonspringresttemplate

How to use Rest Template to step into a JSON object?


I have learned how to use a rest template to access a JSON array like this:

[
    {
        "ID": "0ae6496f-bb0b-4ebd-a094-ca766e82f3e7",
        "Confirmed": 0,
    }
    {
        "ID": "e010ced5-c7cb-4090-a7ed-206f4c482a5b",
        "Confirmed": 0,
    }
]

I accessed the Confirmed for example with

public Model[] getModel() {
    ResponseEntity<Model[]> response = restTemplate.getForEntity(apiUrl, Model[].class);
    return response.getBody();
}

but now I have to access data in another Json from another API. The data looks like this

{
    "prefixes": [
        {
            "region": "ap-northeast-2",
            "service": "AMAZON",
        },
        {
            "region": "eu-west-3",
            "service": "AMAZON",
        }
    ]
}

How can I access region or service inside, and what would be the proper name for this?

The first is a JSON array, the second a JSON object?

The first API is simply

https://example.com

Whereas the second is

https://example.com/data.json.


Solution

  • You have to create the POJO for return type:

    List<RegionServiceObject> items;
    

    Where RegionServiceObject looks:

    public class RegionServiceObject {
        private String region;
        private String service;
        // constructors, getters/setters, toString()....
    }
    

    The way of deseariliseing to object is similar to which you already wrote:

    RegionServiceObject[] items = restTemplate.getForObject(url, RegionServiceObject[].class);
    

    and access for specific item will be as usual for specific item:

    for (RegionServiceObject item : items) {
        item.getRegion();
        item.getService();
        // use them here
    }