I have a class A, with a property Pojo p
.
class A {
Pojo p;
}
I have a custom Serializer for Pojo, but I didn't find any way to change the key of Pojo, by default it's serialized as p
.
Is there any way to change the key p
to something else, like
{
"some_other_key": {/* json for Pojo goes here*/}
}
I can't use jackson annotations because this is a class from a lib.
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);
}
}
In a nutshell, use jsonGenerator.
jsonGenerator.writeStartObject();
jsonGenerator.writeNumberField("firstField", pojo.getFirstField());
jsonGenerator.writeEndObject();
You also need a custom serializer for A itself, not just "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();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.