java - Naming a json property after a variable value -


i using jackson provider rest service:

<jaxrs:server id="services" address="/">     <jaxrs:servicebeans>         <bean class="..."/>     </jaxrs:servicebeans>      <jaxrs:providers>         <bean class="org.codehaus.jackson.jaxrs.jacksonjsonprovider" />     </jaxrs:providers> </jaxrs:server> 

i have class:

public class response {     private date mydate;     private dataobject data; //data related date } 

and method returning json:

@produces("application/json") public response getresp(){        response r = ...        return r; } 

this translates in following json object

{    "mydate":"20150730",    "data":{          "p1":"v1",          "p2":"v2"           } } 

is possible obtain this, instead:

"20150730":{          "p1":"v1",          "p2":"v2"           } 

in other words have mydate content actual json property , data content json value?

you write own serializer. example

import java.io.ioexception; import java.text.simpledateformat; import org.codehaus.jackson.jsongenerator; import org.codehaus.jackson.jsonprocessingexception; import org.codehaus.jackson.map.jsonserializer; import org.codehaus.jackson.map.serializerprovider;  public class responseserializer extends jsonserializer<response> {      @override     public void serialize(response resp, jsongenerator jg, serializerprovider sp)              throws ioexception, jsonprocessingexception {         jg.writestartobject();         string datestring = new simpledateformat("yyyymmdd").format(resp.mydate);         jg.writeobjectfield(datestring, resp.data);         jg.writeendobject();     }  } 

i don't know date object is. assumed java.util.date created formatter. serializer add date string key , objectdata , value.

then need register serializer objectmapper. can in contextresolver (which jax-rs way configure mapper)

@provider public class objectmappercontextresolver implements contextresolver<objectmapper>{      private final objectmapper mapper;      public objectmappercontextresolver() {         mapper = new objectmapper();         simplemodule module = new simplemodule(                 "responsemodule", new version(1, 0, 0, null)         );         module.addserializer(response.class, new responseserializer());         mapper.registermodule(module);     }      @override     public objectmapper getcontext(class<?> type) {         return mapper;     } } 

then register objectmappercontextresolver other provider in xml config.


Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -