java - How do I Gson-serialize an object extending a Collection? -


i have class want serialize:

class enrichedlist extends arraylist<string> {     long timestamp = system.currenttimemillis(); } 

the out-of-the-box gson serializer ignores timestamp field because it's in collection class. know can write typeadapter , manually handle class, , might solution go for, want explore options. there better option scales , maintains better? think of scenario when new developer enters team , adds field/property enrichedclass without knowing has update typeadapter simultaneously.

evidence issue:

class enrichedlist extends arraylist<string> {     long timestamp = system.currenttimemillis(); }  class simpleobject {     long timestamp = system.currenttimemillis(); }   @test public void serializeit() {     enrichedlist list = new enrichedlist();     list.add("fred");     list.add("flintstone");     system.out.println("enriched list: " + new gson().tojson(list));     system.out.println("simple object: " + new gson().tojson(new simpleobject())); } 

produces output:

enriched list: ["fred","flintstone"] simple object: {"timestamp":1418739904470} 

desired output (example):

enriched list: {"timestamp":1418739904470, "list": ["fred","flintstone"]} simple object: {"timestamp":1418739904470} 

so given edit, corrected json of

{"timestamp":1418739904470, "list": ["fred","flintstone"]} 

you have ask key list comes from. if collection set? if else? gson doesn't have such defaults.

the appropriate solution, in opinion, use composition on inheritance (obviously, if that's possible).

class enrichedlist {     long timestamp = system.currenttimemillis();     arraylist<string> list = new arraylist<string>(); } 

gson have no trouble serializing json want.


Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -