Reputation: 18573
I have this class which I want to serialize:
class EnrichedList extends ArrayList<String> {
long timestamp = System.currentTimeMillis();
}
The out-of-the-box Gson
serializer ignores the timestamp field because it's in a collection class. I know I can write a TypeAdapter and manually handle the class, and it might be the solution I go for, but I want to explore my options. Are there any better option which scales and maintains better? Think of the scenario when a new developer enters the team and adds a field/property to the EnrichedClass
without knowing he has to update the TypeAdapter simultaneously.
Evidence for my 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 this output:
Enriched list: ["Fred","Flintstone"]
Simple object: {"timestamp":1418739904470}
Desired output (example):
Enriched list: {"timestamp":1418739904470, "list": ["Fred","Flintstone"]}
Simple object: {"timestamp":1418739904470}
Upvotes: 1
Views: 670
Reputation: 279920
So given your edit, with corrected JSON of
{"timestamp":1418739904470, "list": ["Fred","Flintstone"]}
you have to ask yourself where the key list
comes from. What if your collection was a Set
? What if it was something else? Gson doesn't have such defaults.
The most appropriate solution, in my opinion, is to use composition over inheritance (obviously, only if that's possible).
class EnrichedList {
long timestamp = System.currentTimeMillis();
ArrayList<String> list = new ArrayList<String>();
}
Gson will have no trouble serializing that to the JSON you want.
Upvotes: 3