[英]Jackson change the key of a value without using annotation
我有一個 class A,有一個屬性Pojo p
。
class A {
Pojo p;
}
我有一個用於 Pojo 的自定義序列化器,但我沒有找到任何方法來更改 Pojo 的密鑰,默認情況下它被序列化為p
。
有什么方法可以將密鑰p
更改為其他內容,例如
{
"some_other_key": {/* json for Pojo goes here*/}
}
我不能使用 jackson 注釋,因為這是來自 lib 的 class。
public class PojoSerializer extends StdSerializer<Pojo> {
@Override
public void serialize(Pojo pojo, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
//how can I set the key of this Pojo?
jsonGenerator.writeObject(pojo);
}
}
簡而言之,使用 jsonGenerator。
jsonGenerator.writeStartObject();
jsonGenerator.writeNumberField("firstField", pojo.getFirstField());
jsonGenerator.writeEndObject();
您還需要 A 本身的自定義序列化程序,而不僅僅是“Pojo”。
public class PojoSerializer extends StdSerializer<A> {
public SaleBoSerializer(Class<A> t) {
super(t);
}
@Override
public void serialize(A a, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeStartObject();
jsonGenerator.writeObjectField("custom_field_name", a.pojo)
jsonGenerator.writeEndObject();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.