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?

1

1 Answer 1

5

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");
        }
    }
Sign up to request clarification or add additional context in comments.

2 Comments

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<String> departName;
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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.