Search code examples
javajsonjacksonjson-deserializationjackson-databind

Deserializing JSON objects wrapped inside unnamed root object using Jackson


I have to work with an API that returns all objects wrapped in a unnamed root object. Something like this:

{
  "user": {
    "firstname":"Tom",
    "lastname":"Riddle"
  }
}

Here, I am interested in deserializing the user object only. But given the nature of the response, I will have to write a class that wraps the user object if I want to deserialize it successfully.

@Getter
@Setter
@ToString
// Wrapper class
public class Info {
    private User user;
}

and then

@Getter
@Setter
@ToString
public class User {
    private String firstname;
    private String lastname;
}

All responses of the API return the response in this manner, so I am looking for a way to deserialize the response in such a way as to have one generic wrapper class that can be used to extract any type of JSON object.

I have tried this:

@Getter
@Setter
public class ResponseWrapper<T> {
    private T responseBody;

}

and then

ResponseWrapper<User> userInfo = objectMapper.readValue(response.body().string(), ResponseWrapper.class);

But this results in the following exception:

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "user" (class com.redacted.response.ResponseWrapper), not marked as ignorable (one known property: "responseBody"])

So, is there any way for me to deserialize this response without having to write separate wrapper classes for each API response like this?


Solution

  • You can do something like this:

    JsonNode jsonNode = objectMapper.readTree(response.body().string());
    String content = jsonNode.elements().next().toString();
    User user = objectMapper.readValue(content, User.class);
    

    Output:

    User(firstname=Tom, lastname=Riddle)