Jackson-databind 映射 JSON 跳过图层

Jackson-databind mapping JSON skip layer

我得到了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 一个路径,这样它就可以跳过“响应”层。

您可以使用 @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;
}

欢迎来到 Stack Overflow。您可以为 Collection<ResponseEntry> 集合定义包装器 class,如下所示:

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

ResponseEntry class 可以定义如下:

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

    @JsonProperty("value")
    private String value;
}

一旦定义了这些 classes,您就可以像下面这样重写旧的 Response class :

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