[英]Jackson deserialize json property into object
I need to deserialize the following json: 我需要反序列化以下json:
{
//...
"foo_id":1
//...
}
Into an object of class Foo with its id
property set to the foo_id
json property. 进入Foo类的
id
属性设置为foo_id
json属性的对象。
I need to do this within a custom deserializer. 我需要在自定义反序列化器中执行此操作。 What is the most easy way to accomplish this?
实现此目的的最简单方法是什么?
I was thinking to somehow "transform" the json to 我在想以某种方式将json“转换”为
{
//...
"foo_id":{
"id":1
}
//...
}
and then delegate this back to Jackson. 然后将其委托给杰克逊。
In this case, the object is of type Foo, but there are others which might not be of this class. 在这种情况下,该对象的类型为Foo,但是有些对象可能不是此类。 Also, in this case, that json is a number, but I would like to support if it was a string as well.
另外,在这种情况下,该json是一个数字,但我也想支持它是否也是字符串。 So, I need a kind of generic way to do this, that's why I think delegating back to Jackson might be a good idea.
所以,我需要一种通用的方式来做到这一点,这就是为什么我认为委派杰克逊可能是一个好主意。
No annotations allowed. 不允许注释。 Suppose you're already writing the Deserializer for this property.
假设您已经在为此属性编写反序列化器。
Take a look at this . 看看这个 。 Here is a code that I think might help you to get some ideas.
我认为这是一个代码,可以帮助您获得一些想法。
public class MyDeserializer extends JsonDeserializer< Message >
{
@Override
public Message deserialize( JsonParser jp, DeserializationContext arg1 ) throws IOException,
JsonProcessingException
{
ObjectMapper mapper = (ObjectMapper) jp.getCodec();
ObjectNode root = (ObjectNode) mapper.readTree(jp);
Class<? extends Message> subClass = null;
Iterator<Entry<String, JsonNode>> elementsIterator = root.getFields();
while (elementsIterator.hasNext())
{
Entry<String, JsonNode> element = elementsIterator.next();
String name = element.getKey();
if ("foo_id".equals(name))
{
if(element.getValue().isInt())
subClass = FooInteger.Class;
break;
}
}
if (subClass == null) return null;
return mapper.readValue(root, subClass);
}
}
Have you considered use of mix-in annotations ? 您是否考虑过使用混合注释 ? With Jackson 2.2, you could also use converters to do two-step processing (
@JsonDeserialize(converter=MyConverter.class
). 使用Jackson 2.2,您还可以使用转换器进行两步处理(
@JsonDeserialize(converter=MyConverter.class
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.