简体   繁体   English

使用Jackson进行接口的反序列化,其中接口实现在序列化对象中指定

[英]Deserialization of interfaces using Jackson, where the interface implementation is specified in the serialized object

I have the following sort of structure (simplified to hopefully make the problem clearer): 我具有以下类型的结构(简化后希望可以使问题更清楚):

interface Settings {
    ...
}

interface Component {
    ...
}

class Container {
    Class<? extends Component> component;
    Settings settings;
}

@SettingsClass(MySettings.class)
class MyComponent implements Component{
    ...
}

class MySettings implements Settings{
    ...
}

If I serialize an instance of Container using Jackson, I get a JSON that looks a bit like: 如果使用Jackson序列化Container的实例,则会得到一个类似于以下内容的JSON:

{
    component: "my.package.MyComponent"
    settings: { ... }
}

This is exactly what I want. 这正是我想要的。

But I can't deserialize that JSON because Jackson doesn't know which implementation of Settings to use. 但是我无法反序列化该JSON,因为杰克逊不知道要使用哪种设置实现。 At run time, I can retrieve the SettingsClass annotation and identify which class the settings field should be deserialized to. 在运行时,我可以检索SettingsClass批注并确定settings字段应反序列化到哪个类。

Is there a way for me to get Jackson to partially deserialize the JSON, and then have it deserialize the rest (ie the settings ) once I've been able to inspect the component and determine which Settings class to use? 我有办法让Jackson进行部分反序列化JSON,然后一旦我能够检查component并确定要使用哪个Settings类,就可以对其余部分(即settings )进行反序列化?

Not really. 并不是的。 I had to do something similar recently. 最近我不得不做类似的事情。 I parsed into JsonNode and checked the property manually. 我解析为JsonNode并手动检查了该属性。

final JsonNode jsonRoot = new ObjectMapper().readTree(jsonString);
//...
Optional.ofNullable(jsonRoot.get("component")).map(JsonNode::textValue) ...

Then serialized the tree into the POJO. 然后将树序列化为POJO。

new ObjectMapper().readerFor(theClass).readValue(jsonRoot)

Not amazing, but saves parsing the entire string twice at least. 并不令人惊讶,但是至少可以将整个字符串解析两次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM