【发布时间】:2018-06-03 20:19:15
【问题描述】:
我尝试将以下 json 反序列化为 POJO。
{
"foo": {
"key1":"dummy",
"key2":"dummy"
},
"bar": {
"key1":"dummy",
"key2":"dummy",
"key3":"dummy"
},
"bazKey1":"dummy",
"bazKey2":"dummy",
"bazKey3":"dummy",
"bazKey4":"dummy"
// Many others....
}
你可以看到上面奇怪的baz属性...
但我想将baz 视为像foo 和bar 这样的对象。
public class Pojo {
private Foo foo;
private Bar bar;
private Baz baz;
// Many others....
}
但是,我发现使用自定义反序列化器的解决方案很差。
糟糕的解决方案
@Override
public Pojo deserialize(JsonParser p, DeserializationContext ctxt) throws Exception {
ObjectCodec codec = p.getCodec();
JsonNode node = codec.readTree(p);
Baz baz = new Baz.Builder()
.key1(node.get("bazKey1").textValue())
.key2(node.get("bazKey2").textValue())
.key3(node.get("bazKey3").textValue())
.key4(node.get("bazKey4").textValue())
.build();
// We have to write annoying (setter/constructor/builder) instead of below method.
// return codec.treeToValue(node, Pojo.class);
return new Pojo.Builder()
.foo(foo)
.bar(bar)
.baz(baz)
.other(other)
.other(other)
.other(other) // Many others...
.build();
}
这个解决方案迫使我们使用烦人的(setter/constructor/builder)。
如何使用 jackson 将字段反序列化为对象?
此外,这个 POJO 是 不可变 对象。
【问题讨论】:
-
我认为您正在寻找使用 JsonIdentityInfo 注释概述的引用。
-
你可以有一个包装 Foo 和 Bar 的 Baz 类
-
看起来
Foo、Bar、Baz类具有相同的属性。是真的吗? “许多其他...”表示您还有其他POJOs,看起来像Foo,Bar? -
抱歉含糊不清。我更新了我的问题。这与循环引用无关。
Foo和Bar也只是示例。 -
@MichałZiober 是的,我有 10 多个
POJO,例如Foo和Bar。