java - Gson transform a field into multiple fields -


say have serialized following object json string:

class person {     public final string name;     public person(string name) { this.name = name; } }  person p = new person("bob falaway"); jsonobject json = gson.tojsontree(p, person.class).getasjsonobject(); 

now want deserialize it, want split split name 2 fields, firstname , lastname. how do this?

i want end result in class similar to:

class refinedperson {     public final string firstname;     public final string lastname;      public string tostring() { return string.format("%s %s", firstname, lastname); } } 

is @ possible gson?

register own jsonserializer type (or typeadapter if you'd prefer)?

something like:

@jsonadapter(personserializer.class) class person {     private final string name;     person(final string name) {         // validation...         this.name = name;     }      string getname() {         return this.name;     } } 

where serialiser looks like:

class personserializer implements jsonserializer<person> {     @override     public jsonobject serialise(final person src,                                 final type persontype,                                 final jsonserializationcontext context) {          final jsonobject json = new jsonobject();         final string[] names = src.getname().split(" ");         // validation...          json.addproperty("firstname", names[0]);         json.addproperty("lastname", names[1]);         return json;     } } 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -