[英]Jackson custom deserializer mapping
I need to deserialize some json which can contain either an array of objects [{},{}] or a single object {}. 我需要反序列化一些json,其中可以包含对象数组[{},{}]或单个对象{}。 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"?
以及如何告诉Jackson将反序列化器用于“位置”属性?
Here is how the Json can look : 这是Json的外观:
{ {
"location":
[
{
"code":"75",
"type":"1"
},
{
"code":"77",
"type":"1"
}
]
}
or 要么
{
"location":
{
"code":"75",
"type":"1"
}
}
I don't know what your JSON looks like, but I think using ObjectNode is a lot easier for this case than using JsonDeserializer
. 我不知道您的JSON是什么样的,但是我认为在这种情况下使用ObjectNode比使用
JsonDeserializer
容易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>
}
You can tell Jackson to use this deserializer with the Annotation JsonDeserialize . 您可以告诉Jackson将此反序列化器与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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.