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

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

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

好吧,尽管我个人从来没有那样使用过杰克逊,但确实可以这样做。您可以将其反序列化为

JsonNode
对象,然后将其转换为正确的类型

final ObjectMapper objectMapper = new ObjectMapper();final MyClass myClass = new MyClass();myClass.foo = "bar";// Serializefinal String json = objectMapper.writevalueAsString(myClass);// Deserializefinal JsonNode jsonNode = objectMapper.readTree(json);// Get the @typefinal String type = jsonNode.get("@type").asText();// Create a Class-objectfinal Class<?> cls = Class.forName(type);// And convert itfinal Object o = objectMapper.convertValue(jsonNode, cls);System.out.println(o.getClass());

输出为:

我的课



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4953199.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-13
下一篇 2022-11-13

发表评论

登录后才能评论

评论列表(0条)

保存