After much exploration, I have discovered a solution using TypeAdapterFactory.
Below is the implementation:
class AutosaveAdapter implements TypeAdapterFactory {
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> tokenType) {
final TypeAdapter<T> adapter = gson.getDelegateAdapter(this, tokenType);
return new TypeAdapter<T>() {
@Override
public T read(JsonReader reader) throws IOException {
return adapter.read(reader);
}
@Override
public void write(JsonWriter writer, T value) throws IOException {
JsonElement tree = adapter.toJsonTree(value);
if (value instanceof Autosave) {
String dom = value.toString();
JsonObject jo = (JsonObject) tree;
jo.addProperty("autosave", dom );
}
gson.getAdapter(JsonElement.class).write(writer, tree);
}
};
}
}
Furthermore,
class Autosave {
int waitingTime;
@Expose(serialize = false, deserialize = false)
String name;
@Expose(serialize = false, deserialize = false)
String arguments;
@Expose(serialize = false, deserialize = false)
String body;
Autosave(int waitingTime, String name, String arguments, String body) {
this.waitingTime = waitingTime;
this.name = name;
this.arguments = arguments;
this.body = body;
}
public String toString() {
return "{ waitingTime:" + waitingTime + "," +
name +" ( "+arguments+" ) { " + body + " } "+
"}";
}
}
To perform a test:
public static void main(String... args) {
Autosave autosave = new Autosave(2000, "save", "editor", "return editor.saveData( editor.id, editor.getData() );");
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setLenient();
Gson gson = gsonBuilder
.excludeFieldsWithoutExposeAnnotation()
.registerTypeAdapterFactory(new AutosaveAdapter())
.create();
System.out.println(gson.toJson(autosave));
}