小编典典

当json包含type属性时,杰克逊能否确定要反序列化的根对象类型?

json

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

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

以json为例:

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

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

objectMapper.readValue(value, Object.class);

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


阅读 701

收藏
2020-07-27

共1个答案

小编典典

好吧,尽管我个人从来没有那样使用过杰克逊,但确实可以这样做。您可以将其反序列化为JsonNode对象,然后将其转换为正确的类型。

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());

输出为:

我的课

2020-07-27