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}