Home » Java » java – Webclient map nested object-Exceptionshub

java – Webclient map nested object-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m using WebClient to consume ai API

The node I need from the response is nested inside

example API response

{
    "api": {
        "results": 129,
        "countries": [
            {
                "country": "Albania",
                "code": "AL",
                "flag": "https:\/\/media.api-football.com\/flags\/al.svg"
            },
            {
                "country": "Algeria",
                "code": "DZ",
                "flag": "https:\/\/media.api-football.com\/flags\/dz.svg"
            }

        ]
    }
}

I only need to map each country to a POJO but the only way I was able to do it so was by composing complex objects in order to achieve the same representation as to the API response.

public class CountryResponse {
    private Countries api;
}

public class Countries {
    private int results;
    private List<Country> countries;
}

public class Country {
    private String country;
    private String code;
    private String flag
}

And then I call the API

CountryResponse countryResponse = webClient
            .get()
            .uri("countries")
            .retrieve()
            .bodyToMono(CountryResponse.class)
            .block();

I would like to avoid the need for creating very complex objects only to be able to map a given node inside the JSON response from the API

How to&Answers:

I only need to map each country to a POJO but the only way I was able
to do it so was by composing complex objects

Pardon me but I fail to see any complex objects provided in your example. On the contrary a POJO is the simplest object there is in the language. It’s just a data container without any behavior.

So what you’re doing is fetching some data from an API and flesh it out in POJOs in order to use them in your application. I see nothing wrong with that.

Now, if you want to simplify so bad you could do something about Countries.results since you may obtain that information from Countries.countries.Size(), but again I’m not sure if it’s worth the effort or if it’s going to put you in more trouble.