How to convert below JSON to POJO using ObjectMapper of Jackson

走远了吗. 提交于 2021-01-29 03:03:41

问题


I am trying below code to convert below JSON to POJO using ObjectMapper class of Jackson but it's throwing exception. Could anyone help me to resolve this issue. Actually JSON is given by UI so can't change format of it. I need to parse this JSON to java object using Jackson library.

JSON: data.json

{
    "0": {
        "location": "6",
        "userType": "1",
        "isActive": "1",
        "userId": "Shailesh@gmail.com"
    },
    "1": {
        "location": "7",
        "userType": "2",
        "isActive": "1",
        "userId": "Vikram@gmail.com"
    }
}

DTOs:

public class UsersList {
    List<UserDetails> users;
}

public class UserDetails {
    private String userId;
    private String location;
    private String userType;
    private String isActive;

    public String getUserId() {
        return userId;
    }
    public void setUserId(String userId) {
        this.userId = userId;
    }
    public String getLocation() {
        return location;
    }
    public void setLocation(String location) {
        this.location = location;
    }
    public String getUserType() {
        return userType;
    }
    public void setUserType(String userType) {
        this.userType = userType;
    }
    public String getIsActive() {
        return isActive;
    }
    public void setIsActive(String isActive) {
        this.isActive = isActive;
    }
}

Test Class: HandlerUtil

import java.io.IOException;
import java.io.InputStream;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mcmcg.ams.lambda.model.UserDetails;

public class HandlerUtil {
    private static final Logger LOG = LogManager.getLogger(HandlerUtil.class);

    private HandlerUtil() {
    }

    public static void main(String[] args) {
        try (InputStream instream = HandlerUtil.class.getClassLoader().getResourceAsStream("data.json")) {
            UserDetails sample = new ObjectMapper().readValue(instream, UsersList.class);
            System.out.println(sample.toString());
        } catch (IOException ex) {
            LOG.error("Exception occurred while laoding data.json file : ", ex);
        }
    }
}

Exception: com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input


回答1:


You can use ObjectMapper.readValue() method of jackson.

I think your solution will be like this :

    String jsonBody = yourJson;
    ObjectMapper objectMapper = new ObjectMapper();
    try {
        UserDetailsMapDao userDetailsMapDao = objectMapper
                .readValue(jsonBody, UserDetailsMapDao.class);
    } catch (JsonParseException e) {
        // TODO Exception Handling
    } catch (JsonMappingException e) {
        // TODO Exception Handling
    } catch (IOException e) {
        // TODO Exception Handling
    }

Your Daos will be like this :

public class UserDetailsMapDao {

private Map<String, UserDetails> userDetailsMap;

public String getUserDetailsMap() {
return userDetailsMap;
}
public void setUserDetailsMap(String userDetailsMap) {
this.userDetailsMap = userDetailsMap;
}

}

public class UserDetails {

private String userId;
private String location;
private String userType;
private String isActive;

public String getUserId() {
    return userId;
}
public void setUserId(String userId) {
    this.userId = userId;
}
public String getLocation() {
    return location;
}
public void setLocation(String location) {
    this.location = location;
}
public String getUserType() {
    return userType;
}
public void setUserType(String userType) {
    this.userType = userType;
}
public String getIsActive() {
    return isActive;
}
public void setIsActive(String isActive) {
    this.isActive = isActive;
}

}




回答2:


The JSON is in format of Map<String, UserDetails> take a look at that, key 0 has user "Shailesh@gmail.com" and key 1 with "Vikram@gmail.com"

TypeReference<HashMap<String,UserDetails>> typeRef 
        = new TypeReference<HashMap<String,UserDetails>>() {};

HashMap<String,UserDetails> sample = new ObjectMapper()
                                  .readValue(instream, typeRef);

If using jackson use @JsonAnySetter

public class UsersList {

private Map<String, UserDetails> users = new HashMap<>();

@JsonAnySetter
public void setUsers(String name, UserDetails value) {
this.addressDetails.put(name, value);
    }

 }

And then map it to UserDetails

 UserDetails sample = new ObjectMapper().readValue(instream, UsersList.class);



回答3:


Firstly, before you can deserialize your json string to DTOs, the DTOs should contain no-argument constructor, getters and setters. Your currect DTOs would match a string like the one below.

{
    "users": [
        {
            "location": "6",
            "userType": "1",
            "isActive": "1",
            "userId": "Shailesh@gmail.com"
        },
        {
            "location": "7",
            "userType": "2",
            "isActive": "1",
            "userId": "Vikram@gmail.com"
        }
    ]
}

The DTO that would match the string example provided above would be like the following.

public class UsersList {
    UserDetails zero;
    UserDetails one;

    public UsersList() {
    }

    public UserDetails getZero() {
        return zero;
    }

    public void setZero(final UserDetails zero) {
        this.zero = zero;
    }

    public UserDetails getOne() {
        return one;
    }

    public void setOne(final UserDetails one) {
        this.one = one;
    }
}


来源:https://stackoverflow.com/questions/55147518/how-to-convert-below-json-to-pojo-using-objectmapper-of-jackson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!