繁体   English   中英

Jackson自定义解串器映射

[英]Jackson custom deserializer mapping

我需要反序列化一些json,其中可以包含对象数组[{},{}]或单个对象{}。 看看我的问题 这是我想做的事情:

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

但是我被困在这里。 如何重新映射对象? 以及如何告诉Jackson将反序列化器用于“位置”属性?

这是Json的外观:

{

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

要么

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

我不知道您的JSON是什么样的,但是我认为在这种情况下使用ObjectNode比使用JsonDeserializer容易JsonDeserializer 像这样:

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

您可以告诉Jackson将此反序列化器与Annotation JsonDeserialize一起使用。

在反序列化方法中,您可以使用以下代码:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM