假设序列化为json包含实际对象的类名,在Class上使用此批注:
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@type")
class MyClass {
String foo;
}
Run Code Online (Sandbox Code Playgroud)
所以json就是这样的:
{"@type": "com.example.MyClass", "foo": "bar"}
Run Code Online (Sandbox Code Playgroud)
可以在不指定类型的情况下反序列化吗?我的意思是甚至不是超级型.就像这样:
objectMapper.readValue(value, Object.class);
Run Code Online (Sandbox Code Playgroud)
它实际上没有用,它带回了一张地图.
嗯,我当然可以做到这一点,尽管我个人从未使用过杰克逊.您可以将其反序列化为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());
Run Code Online (Sandbox Code Playgroud)
输出是:
我的课
| 归档时间: |
|
| 查看次数: |
10684 次 |
| 最近记录: |