[英]Deserialization of interfaces using Jackson, where the interface implementation is specified in the serialized object
我具有以下类型的结构(简化后希望可以使问题更清楚):
interface Settings {
...
}
interface Component {
...
}
class Container {
Class<? extends Component> component;
Settings settings;
}
@SettingsClass(MySettings.class)
class MyComponent implements Component{
...
}
class MySettings implements Settings{
...
}
如果使用Jackson序列化Container
的实例,则会得到一个类似于以下内容的JSON:
{
component: "my.package.MyComponent"
settings: { ... }
}
这正是我想要的。
但是我无法反序列化该JSON,因为杰克逊不知道要使用哪种设置实现。 在运行时,我可以检索SettingsClass批注并确定settings
字段应反序列化到哪个类。
我有办法让Jackson进行部分反序列化JSON,然后一旦我能够检查component
并确定要使用哪个Settings
类,就可以对其余部分(即settings
)进行反序列化?
并不是的。 最近我不得不做类似的事情。 我解析为JsonNode并手动检查了该属性。
final JsonNode jsonRoot = new ObjectMapper().readTree(jsonString);
//...
Optional.ofNullable(jsonRoot.get("component")).map(JsonNode::textValue) ...
然后将树序列化为POJO。
new ObjectMapper().readerFor(theClass).readValue(jsonRoot)
并不令人惊讶,但是至少可以将整个字符串解析两次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.