简体   繁体   English

与Jackson反序列化时,重用父对象的值来构造子对象

[英]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: Childversion字段只是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. 我考虑过使用@JacksonInjectversion传递给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注册注入值的任何方法: DeserializationContextfindInjectableValue方法只能让我们查找这样的值。

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.

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