当json包含type属性时,jackson能否确定要反序列化的根对象类型? [英] Can jackson determine root object type to deserialize to when json includes type property?

查看:420
本文介绍了当json包含type属性时,jackson能否确定要反序列化的根对象类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设序列化为json包含实际对象的类名,在类上使用此注释:

Assume serialization to json includes the class name of the actual object, using this annotation on the Class:

@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@type")
class MyClass {
    String foo;
}

所以json是例如:

{"@type": "com.example.MyClass", "foo": "bar"}

这可以反序列化而不指定类型吗?我的意思是甚至不是超级型。就像这样:

Can this be deserialized without specifying the type? And I mean not even the super type. Just something like:

objectMapper.readValue(value, Object.class);

这实际上不起作用,它会带回一张地图。

which doesn't actually work, it brings back a Map.

推荐答案

嗯,这当然可以做到这一点,尽管我个人从未使用过杰克逊。您可以将其反序列化为 JsonNode 对象,然后将其转换为正确的类型。

Well, it is certainly possible to do that although I have personally never used Jackson that way. You can deserialize it to a JsonNode object and then convert it to the proper type.

final ObjectMapper objectMapper = new ObjectMapper();
final MyClass myClass = new MyClass();
myClass.foo = "bar";

// Serialize
final String json = objectMapper.writeValueAsString(myClass);

// Deserialize
final JsonNode jsonNode = objectMapper.readTree(json);

// Get the @type
final String type = jsonNode.get("@type").asText();

// Create a Class-object
final Class<?> cls = Class.forName(type);

// And convert it
final Object o = objectMapper.convertValue(jsonNode, cls);

System.out.println(o.getClass());

输出为:


MyClass

MyClass

这篇关于当json包含type属性时,jackson能否确定要反序列化的根对象类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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