基于gson的解决方案:
//实现的一个InterfaceAdapter
public final class InterfaceAdapter<T> implements JsonSerializer<T>, JsonDeserializer<T> {
public JsonElement serialize(T object, Type interfaceType, JsonSerializationContext context) {
final JsonObject wrapper = new JsonObject();
wrapper.addProperty("type", object.getClass().getName());
wrapper.add("data", context.serialize(object));
return wrapper;
}
public T deserialize(JsonElement elem, Type interfaceType, JsonDeserializationContext context) throws JsonParseException {
final JsonObject wrapper = (JsonObject) elem;
final JsonElement typeName = get(wrapper, "type");
final JsonElement data = get(wrapper, "data");
final Type actualType = typeForName(typeName);
return context.deserialize(data, actualType);
}
private Type typeForName(final JsonElement typeElem) {
try {
return Class.forName(typeElem.getAsString());
} catch (ClassNotFoundException e) {
throw new JsonParseException(e);
}
}
private JsonElement get(final JsonObject wrapper, String memberName) {
final JsonElement elem = wrapper.get(memberName);
if (elem == null) throw new JsonParseException("no '" + memberName + "' member found in what was expected to be an interface wrapper");
return elem;
}
}
//实现
public static void main(String[] args){
YourInterface interface= new YourInterfaceImplementation();
//新建gson对象,并注册类型适配器,注册你对象中所有的接口对象后,反序列化时,会将会找到你接口对象对应的实现类。详见上文中的类
Gson gson = new GsonBuilder().registerTypeAdapter(YourInterface.class, new InterfaceAdapter<YourInterface>())
.create();
String json = gson.toJson(interface,YourInterface.class);
System.out.println(json+ "This is your json string!");
Gson gson1 = new GsonBuilder().registerTypeAdapter(YourInterface.class, new InterfaceAdapter<YourInterface>())
.create();
YourInterface yourDeserializedInterface = gson1.fromJson(json,YourInterface.class);
System.out.println("Deserialized: "+yourDeserializedInterface);
}
网友评论