本文介绍了当 json 包含类型属性时,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 是例如:

So json is for example:

{"@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);

这实际上不起作用,它带回了一个 Map.

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

推荐答案

好吧,虽然我个人从未以这种方式使用过 Jackson,但确实可以这样做.您可以将其反序列化为 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());

输出为:

我的课堂

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

07-31 05:09