java - Jackson serialization: Wrap fields -
there known case when unwrap nested object , write fields main object, , need make inverse task.
i have pojo:
class { private string id = "id1"; @jsonwrap("properties") private string property1 = "..."; @jsonwrap("properties") private string property2 = "..."; // getters , setters } default serializer produce expected
{ "id": "id1", "property1": "...", "property2": "..." } but, json should match specification, , that, need wrap property1 , property2 inside properties wrapper. result should looks like:
{ "id": "id1", "properties": { "property1": "...", "property2": "..." } } i don't want change structure of pojo see 3 possible ways:
- write custom serializer. seems me, write such serializer takes more efforts serialize objects hands.
- create proxy java object reflect right structure of json, , serialize such proxy.
- modify json after have been generated. (i'm afraid great overhead rereading , rewriting of json).
does make such serializer or maybe know options generate json structure need?
for custom serializer want reuse standard beanserializer, dont want write out fields manually:
- hide annotated fields.
- write out bean, without annotated fields, don't close object. (don't call
jgen.writeendobject();) - write out wrapped fields.
- close object.
to functionality without altering model, take @ writing custom serializer accomplish jackson can't figure out natively. annotate model class a specific directions use defined serializer, , use jsongenerator define structure after.
@jsonserialize(using = aserializer.class) class { private string field1; private string innerfield1; private string innerfield2; // getters , setters public static class aserializer extends jsonserializer<a> { @override public void serialize(a value, jsongenerator jgen, serializerprovider provider) throws ioexception, jsonprocessingexception { jgen.writestartobject(); jgen.writestringfield("field1", value.getfield1()); jgen.writeobjectfieldstart("wrapper"); jgen.writestringfield("innerfield1", value.getinnerfield1()); jgen.writestringfield("innerfield2", value.getinnerfield2()); jgen.writeendobject(); jgen.writeendobject(); } } } i used static inner class in case, feasibly can place serializer wherever best fits project structure based on visibility. one-off special case serializers, tend do.
Comments
Post a Comment