[英]Reuse value from parent object to construct child when deserializing with Jackson
I have two classes with a redundant shared attribute: 我有两个带有冗余共享属性的类:
class Parent {
int version;
Child child;
}
class Child {
int version;
String name;
}
The version
field from Child
is just a local copy of the Parent
's own field, so it is represented like this in JSON: Child
的version
字段只是Parent
自己的字段的本地副本,因此在JSON中这样表示:
{
"version": 2,
"child": {
"name": "john"
}
}
I want to deserialize this JSON payload to the corresponding Parent
object with parent.child.version == 2
(the value is copied from the parent). 我想使用
parent.child.version == 2
反序列化此JSON有效负载到相应的Parent
对象(该值是从父级复制的)。 How can I achieve this? 我该如何实现?
I thought about using @JacksonInject
to pass the version
to the Child
, but that requires populating the injected values while deserializing the parent object. 我考虑过使用
@JacksonInject
将version
传递给Child
,但这需要在反序列化父对象的同时填充注入的值。 I could not find any way to register an injected value in a custom deserializer: the findInjectableValue method of DeserializationContext
only lets us look up such a value. 我找不到在自定义反序列
DeserializationContext
注册注入值的任何方法: DeserializationContext
的findInjectableValue方法只能让我们查找这样的值。
It's not really a Jackson-specific solution but it's probably the simplest one: create a PreChild
class whose attributes match the JSON payload, then convert the PreChild
to a Child
in the constructor of Parent
. 这实际上不是特定于Jackson的解决方案,但可能是最简单的解决方案:创建一个
PreChild
类, PreChild
属性与JSON有效负载匹配,然后在Parent
的构造函数PreChild
转换为Child
。
class PreChild {
String name;
public Child withVersion(int version) {
return Child(version, name);
}
}
class Parent {
int version;
Child child;
@JsonCreator
Parent(
@JsonProperty("version") int version,
@JsonProperty("child") PreChild preChild) {
this.version = version;
this.child = preChild.withVersion(version);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.