2

I've got an response from API which I want to get data from. How am I able to map this response to object by RestTemplate but without getting all the fields? I dont want to create nested objects. I'd expect to get result like this:

@JsonProperty("id")
private long id;
@JsonProperty("user.userName") <-- how to achive this?
private String userName;
@JsonProperty("imagies.thumbnail.url") <-- how can i get only this 1 property?
private URL standardResolutionUrlOfPhoto;

Response:

 "data": [
        {
            "id": "xxxxx",
            "user": {
                "username": "xxxxx"    <--- I dont want  to create User user field!
            },
            "images": {
                "thumbnail": {
                    "width": 150,
                    "height": 150,
                    "url": "xxxxxx"
                },
                "low_resolution": {
                    "width": 320,
                    "height": 320,
                    "url": "xxxxx"
                },
                "standard_resolution": {
                    "width": 640,
                    "height": 640,
                    "url": "xxxx"
                }
            },
Mikkes23
  • 29
  • 2
  • I am not sure which framework you are using but I think it is better to create a getter that returns `user.userName` e.g. `public String getUserName(){ return user.userName; };` because your consumer does not need to know how your POJO is implemented or change the server response if you have access to the server. – Enzokie Jul 10 '18 at 06:20

2 Answers2

0

There is a quite cool, but dirty way you can achieve this. Take a look here:

@JsonProperty("id")
private long id;
@JsonIgnore
private String userName;
@JsonIgnore
private String standardResolutionUrlOfPhoto;

@JsonProperty("user")
private void unpackUser(JsonNode user) {
    this.userName = user.get("username").asText();
}

@JsonProperty("images")
private void unpackImages(JsonNode images) {
    this.standardResolutionUrlOfPhoto = images.get("thumbnail").get("url").asText();
}
Halko Karr-Sajtarevic
  • 2,248
  • 1
  • 16
  • 14
0

You can use JsonPath library for reading values using a JSON path.

Similar question is already answered in other question Jsonpath with Jackson or Gson