Jackson custom deserializer mapping

馋奶兔 提交于 2019-12-25 01:53:50

问题


I need to deserialize some json which can contain either an array of objects [{},{}] or a single object {}. See my question. Here is what I'm trying to do :

    public class LocationDeserializer extends JsonDeserializer<List<Location>>{

    @Override
    public List<Location> deserialize(JsonParser jp,
        DeserializationContext ctxt) throws IOException
    {
        List<Location> list = new ArrayList<Location>();
        if(!jp.isExpectedStartArrayToken()){
            list.add(...);
        }else{
            //Populate the list
        }

        return list;
    }

But I'm getting stuck here. How can I remap the object? And how to tell Jackson to use this deserializer for the attribute "location"?

Here is how the Json can look :

{

"location":
    [
        {
            "code":"75",
            "type":"1"
        },
        {
            "code":"77",
            "type":"1"
        }
    ]
}

or

{
"location":
        {
            "code":"75",
            "type":"1"
        }
}

回答1:


You can tell Jackson to use this deserializer with the Annotation JsonDeserialize.

And inside your deserialize method, you could use the following:

@Override
public List<Location> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    List<Location> list = new ArrayList<Location>();
    ObjectMapper mapper = new ObjectMapper();
    JsonNode root = mapper.readTree(jp);
    if(root.get("location").isArray()){
        // handle the array
    }else{
        // handle the single object
    }

    return list;
}



回答2:


I don't know what your JSON looks like, but I think using ObjectNode is a lot easier for this case than using JsonDeserializer. Something like this:

ObjectNode root = mapper.readTree("location.json");
if (root.getNodeType() == JsonNodeType.ARRAY) {
  //Use a get and the JsonNode API to traverse the tree to generate List<Location>
}
else {
  //Use a get and the JsonNode API to traverse the tree to generate single Location or a one-element List<Location>
}


来源:https://stackoverflow.com/questions/21064003/jackson-custom-deserializer-mapping

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