import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
/**
* Only for List type fields.
* @author alexeyz
*/
public class RuntimeClassNameTypeAdapter extends TypeAdapter
- > {
private static final String CLASS_NAME_PROPERTY = "type";
@Override
public void write(JsonWriter out, List
if (src == null) {out.nullValue();return;}
Gson gson = new Gson();
out.beginArray();
for (Object srcBlocker : src) {
JsonElement serializedBlocker = gson.toJsonTree(srcBlocker);
JsonObject blocker = (JsonObject) serializedBlocker;
blocker.addProperty(CLASS_NAME_PROPERTY, srcBlocker.getClass().getSimpleName());
out.jsonValue(blocker.toString());
}
out.endArray();
}
Usage:
@JsonAdapter(RuntimeClassNameTypeAdapter.class)
protected List