Friday, July 13, 2018

How to include class name property when serializing json

import com.google.gson.Gson;
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 src) throws IOException {
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 book;


No comments: