Jackson自定义属性 - 多态属性的类型映射名称 [英] Jackson Custom Property-Name to Type Mapping for Polymorphic Properties

查看:1140
本文介绍了Jackson自定义属性 - 多态属性的类型映射名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试反序列化一个相当复杂的POJO JSON,我需要在其中定义一个特定的属性名称来解析,但是找不到这个相当简单的功能。

I am trying to deserialize a rather complex POJOs JSON, where I would need to define a specific property-name to type resolution, but yet faild fininding this rather simple feature.

假设类如下:

class Example {
  int id;
  Map<String,Object> extras;
}

并且Jackson正在将POJO正确序列化为JSON,其中地图被序列化为键值映射就像预期一样:

and Jackson is serializing the POJO correctly to JSON where the map is serialized to a key-value map just like expected:

{...
id:5,
extras:{object1:{...}, object2:{...}}
...}

现在我想告诉Jackson根据实际类型明确地反序列化extras对象。所以我需要告诉杰克逊以某种方式将object1映射到A型,将object2映射到B型。

now I would like to tell Jackson to explicitly deserialize the extras objects by their actual type. So I need to tell Jackson somehow to map "object1" to Type A and "object2" to type B.

这可能吗?谢谢。

推荐答案

有一个很好的指南如何处理它: http://www.cowtowncoder.com/blog/archives/2010/03/entry_372.html

There is nice guide how to deal with it: http://www.cowtowncoder.com/blog/archives/2010/03/entry_372.html

另一个教程:

http://programmerbruce.blogspot.de/2011/05/deserialize-json-with-jackson-into.html

第二个教程中的第六个示例可以修改,反序列化器将循环使用类似于:

The 6th example from the second tutorial could be modified and deserializer would have loop with something similar to:

Map<String, Class> types = ...// map of supported types
JsonToken token = jsonParser.nextToken();
if(token == JsonToken.FIELD_NAME){ // "object1" etc.
    String name = jsonParser.getCurrentName();
    Class type = types.get(name);
    Object object = jsonParser.readValueAs(type);
}

这篇关于Jackson自定义属性 - 多态属性的类型映射名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆