I have a collection of generated java beans where each bean defines one or more fields, plus it subclasses HashMap<String, T>
where T
is a parameterised type. The generated fields model explicitly-defined schema properties within a JSON schema
, and the subclassing of HashMap
is done to support additional "arbitrary" properties of a specific type (specified by the JSON schema's "additionalProperties" field, for those that are familiar with JSON Schema).
Here is an example of a generated bean:
public class MyModel extends HashMap<String, Foo> {
private String prop1;
private Long prop2;
public String getProp1() {
return prop1;
}
public void setProp1(String value) {
this.prop1 = value;
}
public Long getProp2() {
return prop2;
}
public void setProp2(Long prop2) {
this.prop2 = prop2;
}
}
In this example, the user can set prop1
or prop2
as normal bean properties and can also set arbitrary properties of type Foo
via the Map
's put()
method, where Foo
is just some other user-defined type.
The problem is that, by default, Gson
serialises instances of these generated beans such that only the Map
entries are included in the resulting JSON
string, and the explicitly-defined fields are ignored.
Here is a code snippet showing how I use Gson
to serialise an object:
private String serialize(Object obj) {
return new Gson().toJson(obj);
}
From debugging the serialisation path, I can see that Gson
is selecting its internal MapTypeAdapterFactory
to perform the serialization which, makes sense since only the Map entries end up in the JSON string.
Separately, if I serialize a bean that does NOT subclass HashMap, then Gson
selects its internal ReflectiveTypeAdapterFactory
instead.
I think what I need is to implement my own custom type adapter that essentially combines the functionality of the Reflective
and Map
type adapter factories.
Does this sound like a good plan? Has anyone else done something similar to this and could perhaps provide an example to get me started? This will be my first foray into Gson
custom type adapters.