[英]serialize/deserialize Child property with different property using jackson
I have to POJO class( A and B) 我必须去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;
}
To serialize object A to json I want b_name and while deserialize object AI want b_id; 要将对象A序列化为json,我需要b_name,而反序列化对象AI则需要b_id;
In short, I want to pass b_name of child field with the parent object. 简而言之,我想通过父对象传递子字段的b_name。 While deserialize I will get b_id so it should bind to B object(b_id).
反序列化时,我会得到b_id,因此它应该绑定到B object(b_id)。 so same child object should work with different property while serialize and deserialize.
因此,同一子对象在序列化和反序列化时应具有不同的属性。
from server= {a_id=1, a_name="abc", b="pqr"} 来自服务器= {a_id = 1,a_name =“ abc”,b =“ pqr”}
from client ={a_id=1,a_name="abc",b=1} 来自客户端= {a_id = 1,a_name =“ abc”,b = 1}
b is b_name at serialization and b_id at deserialization. b在序列化时是b_name,在反序列化时是b_id。
Is it possible? 可能吗?
Yes that should be possible. 是的,那应该是可能的。 While serialization, if your b_id is going to be null, and you don't want it to be included in json, you can use :
序列化时,如果您的b_id将为null,并且您不希望将其包含在json中,则可以使用:
@JsonInclude(Include.NON_NULL)
class B {
}
While deserializing, as you are not going to get b_name, you can have @JsonIgnoreProperties(ignoreUnknown = true)
at class B level. 反序列化时,由于不会获得b_name,因此可以在B类级别使用
@JsonIgnoreProperties(ignoreUnknown = true)
。 It tells jackson to ignore any JSON properties that cannot be mapped to an existing java field. 它告诉杰克逊忽略任何无法映射到现有java字段的JSON属性。
If your requirement for inclusion/exclusion of fields is more complex then this, then you can use JsonSerializer and JsonDeserializer . 如果您对字段包含/排除的要求更加复杂,则可以使用JsonSerializer和JsonDeserializer 。 Something like:
就像是:
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.