【问题标题】:serialize/deserialize Child property with different property using jackson使用杰克逊序列化/反序列化具有不同属性的子属性
【发布时间】:2017-04-17 12:55:52
【问题描述】:

我要 POJO 类(A 和 B)

A{
   a_id;
   a_name;
    @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, 
     property="b_name")
   @JsonIdentityReference(alwaysAsId=true)
   B b;
}

B{
    b_id;
    b_name;
 }

要将对象 A 序列化为 json,我想要 b_name,而反序列化对象 A 我想要 b_id;

简而言之,我想将子字段的 b_name 与父对象一起传递。在反序列化时,我会得到 b_id,所以它应该绑定到 B 对象(b_id)。所以同一个子对象在序列化和反序列化时应该使用不同的属性。

来自服务器 = {a_id=1, a_name="abc", b="pqr"}
来自客户端 ={a_id=1,a_name="abc",b=1}
b 是序列化时的 b_name 和反序列化时的 b_id。

有可能吗?

【问题讨论】:

    标签: java json jackson jackson-databind


    【解决方案1】:

    是的,这应该是可能的。 在序列化时,如果您的 b_id 为空,并且您不希望它包含在 json 中,您可以使用:

    @JsonInclude(Include.NON_NULL)
    class B {
    }
    

    在反序列化时,由于您不会获得 b_name,因此您可以在 B 类级别拥有 @JsonIgnoreProperties(ignoreUnknown = true)。它告诉 jackson 忽略任何无法映射到现有 java 字段的 JSON 属性。

    如果您对包含/排除字段的要求比这更复杂,那么您可以使用 JsonSerializerJsonDeserializer。 比如:

    public class MySerializer extends JsonSerializer<A> {
        @Override
        public void serialize(A a, JsonGenerator jGen, SerializerProvider arg2)
                throws IOException, JsonProcessingException {
            jGen.writeStartObject();
            jGen.writeStringField("a_id", a.getA_id());
            jGen.writeStringField("b_name", a.getB().getB_name() );
            jGen.writeEndObject();
        }
    }
    

    【讨论】:

    • 我想要父属性中的子对象属性,@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="b_name") @JsonIdentityReference(alwaysAsId=true)
    • 我想要父 json 中的子对象属性,@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="b_name") @JsonIdentityReference(alwaysAsId=true) 在序列化中,我已经发送 b_name 和父json 和反序列化我将从客户端接收 json 中的 b_id。
    猜你喜欢
    • 2017-12-09
    • 1970-01-01
    • 1970-01-01
    • 2013-07-15
    • 2015-12-23
    • 2016-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多