【问题标题】:Jackson-databind mapping JSON skip layerJackson-databind 映射 JSON 跳过层
【发布时间】:2021-08-12 14:46:27
【问题描述】:

我得到这样的 JSON 响应:

{
  "status": "success",
  "response": {
    "entries": [
      {
        "id": 1,
        "value": "test"
      },
      {
        "id": 2,
        "value": "test2"
      }
    ]
  }
}

我想将它映射到这样的对象上:

public class Response {

    @JsonProperty("status")
    private String status;
    
    @JsonProperty("response.entries")
    private Collection<ResponseEntry> entries;

}

所以我正在寻找一种方法给@JsonProperty 一个路径,以便它可以跳过“响应”层。

【问题讨论】:

    标签: java json jackson jackson-databind


    【解决方案1】:

    欢迎来到 Stack Overflow。您可以为您的 Collection&lt;ResponseEntry&gt; 集合定义一个包装类,如下所示:

    public class ResponseWrapper {
        @JsonProperty("entries")
        private Collection<ResponseEntry> entries;
    }
    

    ResponseEntry 类可以定义如下:

    public class ResponseEntry {
        @JsonProperty("id")
        private int id;
    
        @JsonProperty("value")
        private String value;
    }
    

    一旦定义了这些类,您就可以重写旧的 Response 类,如下所示:

    public class Response {
        @JsonProperty("status")
        private String status;
        
        @JsonProperty("response")
        private ResponseWrapper responseWrapper;    
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用@JsonUnwrapped 注释进行展平。

      你可以这样上课

      public class Response {
      
         private String status;
          
         private Collection<ResponseEntry> entries;
      
      }
      
      public class ResponseEntry {
      
          @JsonUnwrapped
          private Entry entry;
      
      }
      
      pubic class Entry{
      
      private Integer id;
      private String value;
      }
      

      【讨论】:

        猜你喜欢
        • 2020-04-01
        • 1970-01-01
        • 2018-02-28
        • 1970-01-01
        • 2020-08-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多