3

I have a rest endpoint that returns a 3 level nested json like this one:

 {
   "user":{
      "departament":{
         "departInfo":{
            "departName":"String"
         }
      }
   }
}

And I have a java class without the same 3 nested levels:

@JsonIgnorePropertires("ignoreUnknown = true")
class User(){
    String departName
}

When I am making a rest call using restTemplate:

User response = restTemplate.exchange(url, HttpMethod.GET,
                                      request, User.class)

jackson is not mapping the field departName (because it is not at the same nested level I guess) even with the json ignore properties.

How can I map this http json response to my java field ignoring the nested parent jsons?

Blazerg
  • 821
  • 2
  • 13
  • 32
  • 1
    Possible duplicate of [How to map a nested value to a property using Jackson annotations?](https://stackoverflow.com/questions/37010891/how-to-map-a-nested-value-to-a-property-using-jackson-annotations) – Mehtrick Feb 21 '18 at 19:59

1 Answers1

4

You have to map your nested object via a method and @JsonProperty

    @JsonIgnorePropertires("ignoreUnknown = true")
    class User(){
        String departName;

        @JsonProperty("department")
        private void mapDepartmentName(Map<String,Object department) {
            this.departName = ((Map<String,String>)department.get("departInfo")).get("departName");
        }
    }
Mehtrick
  • 518
  • 3
  • 12
  • you mean when you have multiple departments below your user? No it wont, however if you want to do that, a String departName might not be the right type and you should consider a List departName; – Mehtrick Feb 21 '18 at 16:46
  • I have edited my question with the correct json, it has 2 useless parent json (I can't change it) but I don't want to copy that crap structure into my java model. Is your method gonna work even if I have 2 paren jsons? – Blazerg Feb 21 '18 at 16:58