[英]@jsonproperty serialize different pojo elements in the same attribute name
I have a simple pojo 我有一个简单的pojo
public class C {
public String f1;
public Integer f2;
}
At runtime I am sure at most one of the fields is not null (ie if f1
is "hello"
, I'm sure f2
is null
, and vice versa) 在运行时,我确定最多其中一个字段不为null(即,如果f1
为"hello"
,则我确定f2
为null
,反之亦然)
I would like to serialize the object using always the same name; 我想使用始终相同的名称来序列化对象; for example, with 例如,
C c1 = new C();
c1.f1 = "hello"
C c2 = new C();
c2.f2 = Integer.valueOf(99)
I would like to have c1
serialized as {"samekey":"hello"}
and c2
as {"samekey":99}
. 我想将c1
序列化为{"samekey":"hello"}
,将c2
序列化为{"samekey":99}
。
I know I can use @JsonProperty
to set the serialized name, but I cannot set the same name to both the fields. 我知道我可以使用@JsonProperty
设置序列化名称,但是不能在两个字段中都设置相同的名称。
Is there a way to say that? 有没有办法这么说?
Here is the CustomSerializer, checks if f2 value not null then f2 value is copied to f1 and making f2=null.And excluding nulls in the model so always you will get one key&value as other one will be null. 这是CustomSerializer,检查f2值是否不为null,然后将f2值复制到f1并使f2 = null。并且在模型中排除null,因此您总是会得到一个key&value,因为其他键和值将为null。
public class CustomSerializer extends JsonSerializer<C> {
@Override
public void serialize(final C c, final JsonGenerator gen, final SerializerProvider serializers) throws IOException, JsonProcessingException {
if(c.getF2() != null) // considering always you need f1 key && value
{
c.setF1(c.getF2().toString());
c.setF2(null);
}
}
} }
Annotate serializer & notnull in model as 注释序列化器,并在模型中注释为null
@JsonSerialize(using = CustomSerializer.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class C {
private String f1;
private Integer f2;
//getters & setters
}
Hope this is what you are expecting. 希望这就是您的期望。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.