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:

  1. write custom serializer. seems me, write such serializer takes more efforts serialize objects hands.
  2. create proxy java object reflect right structure of json, , serialize such proxy.
  3. 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:

  1. hide annotated fields.
  2. write out bean, without annotated fields, don't close object. (don't call jgen.writeendobject();)
  3. write out wrapped fields.
  4. 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

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -