package com.perforce.spark.repository;
import java.lang.reflect.Type;
import javax.swing.text.AbstractDocument.AbstractElement;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
public class AbstractRepoAdapter implements JsonSerializer<RepoInterface>,
JsonDeserializer<RepoInterface> {
@Override
public JsonElement serialize(RepoInterface src, Type typeOfSrc,
JsonSerializationContext context) {
JsonObject result = new JsonObject();
String primitive = src.getClass().getSimpleName();
result.add("implType", new JsonPrimitive(primitive));
result.add("properties", context.serialize(src, src.getClass()));
return result;
}
@Override
public RepoInterface deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
String type = jsonObject.get("implType").getAsString();
JsonElement element = jsonObject.get("properties");
try {
String className = AbstractElement.class.getPackage() + "." + type;
return context.deserialize(element, Class.forName(className));
} catch (ClassNotFoundException cnfe) {
throw new JsonParseException("Unknown element type: " + type, cnfe);
}
}
}