简体   繁体   中英

Jackson-databind mapping JSON skip layer

I got a JSON response like this:

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

And i want to map it with jackson-databind on an object like this:

public class Response {

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

}

So i'm searching for an way to give @JsonProperty a path so it can skip the layer "response".

Welcome to Stack Overflow. You can define a wrapper class for your Collection<ResponseEntry> collection like below:

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

The ResponseEntry class could be defined like below:

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

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

Once defined these classes you can rewrite your old Response class like below:

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

You can flatten using the @JsonUnwrapped annotation.

You can have your classes like this

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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