简体   繁体   English

将杰克逊的嵌套json映射到java字段

[英]Map nested json with jackson to java field

I have a rest endpoint that returns a 3 level nested json like this one: 我有一个休息端点,它返回一个三级嵌套json,如下所示:

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

And I have a java class without the same 3 nested levels: 我有一个没有相同的3个嵌套级别的java类:

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

When I am making a rest call using restTemplate: 当我使用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. 即使使用json忽略属性,杰克逊也不会映射字段departName(因为我估计它不在同一嵌套级别)。

How can I map this http json response to my java field ignoring the nested parent jsons? 我如何将此http json响应映射到我的java字段而忽略嵌套的父json?

You have to map your nested object via a method and @JsonProperty 您必须通过方法和@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");
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM