杰克逊定制解串器映射 [英] Jackson custom deserializer mapping
本文介绍了杰克逊定制解串器映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要反序列化一些json,它可以包含一个对象数组[{},{}]或一个对象{}。请参阅我的问题。以下是我要做的事情:
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"?
以下是Json的外观:
Here is how the Json can look :
{
"location":
[
{
"code":"75",
"type":"1"
},
{
"code":"77",
"type":"1"
}
]
}
或
{
"location":
{
"code":"75",
"type":"1"
}
}
推荐答案
我不知道你的JSON是什么样的,但我认为使用 ObjectNode 比使用 JsonDeserializer
容易得多。这样的事情:
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>
}
这篇关于杰克逊定制解串器映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文