Search code examples
javaspringhttppojoenvelope

Map enveloped response into a POJO


I am trying to map the following response:

{
    "data": {
        "id": "1574083",
        "username": "snoopdogg",
        "full_name": "Snoop Dogg",
        "profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_1574083_75sq_1295469061.jpg",
        "bio": "This is my bio",
        "website": "http://snoopdogg.com",
        "counts": {
            "media": 1320,
            "follows": 420,
            "followed_by": 3410
        }
}

into an object where I only want to retrieve the username, full_name, and id fields.

Ex: something like:

public class User{
    String id;
    String username;
    String full_name;

   // getters + setters

}

Is there a way of doing this without first having to store the data object into a Map?


Solution

  • Use Jackson API. It should be simple:

    ObjectMapper mapper = new ObjectMapper();
    User user = mapper.readValue(jsonString, User.class); //jsonString is your actual json string.
    

    You might want to tweak your User class to match the JSON string. E.g. your user class needs to have a 'data' field as List<Data> data; where 'Data' is another POJO. You can add the "id", "userName", etc fields in the 'Data' pojo.