Search code examples
javajsonjacksonjackson-databind

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".


Solution

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