java - GSON: How to move fields to parent object -


i'm using google gson transform java object json.

currently i'm having following structure:

"step": {   "start_name": "start",   "end_name": "end",   "data": {     "duration": {       "value": 292,       "text": "4 min."     },     "distance": {        "value": 1009.0,        "text": "1 km"     },     "location": {        "lat": 59.0000,        "lng": 9.0000,        "alt": 0.0     }   } } 

currently duration object inside data object. skip data object , move duration object step object, this:

"step": {   "start_name": "start",   "end_name": "end",   "duration": {     "value": 292,     "text": "4 min."   },   "distance": {      "value": 1009.0,      "text": "1 km"   },   "location": {      "lat": 59.0000,      "lng": 9.0000,      "alt": 0.0   } } 

how can using gson?

edit: i've tried use typeadapter modify step.class, in write-method i'm not able add duration object jsonwriter.

you can writing, , registering custom serializer step, , making sure inside work duration etc, instead of data.

// registering custom serializer: gsonbuilder builder = new gsonbuilder (); builder.registertypeadapter (step.class, new stepserializer ()); gson gson = builder.create (); // use 'gson' work 

the code custom serializer below, i'm writing off top of head. misses exception handling, , might not compile, , slow things create instances of gson repeatedly. represents kind of thing you'll want do:

class stepserializer implements jsonserializer<step> {   public jsonelement serialize (step src,                                 type typeofsrc,                                 jsonserializationcontext context)     {       gson gson = new gson ();       /* whenever step serialized,       serialize contained data correctly.  */       jsonobject step = new jsonobject ();       step.add ("start_name", gson.tojsontree (src.start_name);       step.add ("end_name",   gson.tojsontree (src.end_name);        /* notice how i'm digging 2 levels deep 'data.' adding       json elements 1 level deep 'step' itself.  */       step.add ("duration",   gson.tojsontree (src.data.duration);       step.add ("distance",   gson.tojsontree (src.data.distance);       step.add ("location",   gson.tojsontree (src.data.location);        return step;     } } 

Comments

Popular posts from this blog

jquery - Invalid Assignment Left-Hand Side -

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -