GSon 必须知道与 json 字符串匹配的类。如果你不想用 fromJson() 来提供它,你实际上可以在 Json 中指定它。一种方法是定义一个接口并在其上绑定适配器。
喜欢:
class A implements MyInterface {
// ...
}
public Object decode()
{
Gson gson = builder.registerTypeAdapter(MyInterface.class, new MyInterfaceAdapter());
MyInterface a = gson.fromJson(jsonString, MyInterface.class);
}
适配器可以是这样的:
public final class MYInterfaceAdapter implements JsonDeserializer<MyInterface>, JsonSerializer<MyInterface> {
private static final String PROP_NAME = "myClass";
@Override
public MyInterface deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
try {
String classPath = json.getAsJsonObject().getAsJsonPrimitive(PROP_NAME).getAsString();
Class<MyInterface> cls = (Class<MyInterface>) Class.forName(classPath);
return (MyInterface) context.deserialize(json, cls);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
@Override
public JsonElement serialize(MyInterface src, Type typeOfSrc, JsonSerializationContext context) {
// note : won't work, you must delegate this
JsonObject jo = context.serialize(src).getAsJsonObject();
String classPath = src.getClass().getName();
jo.add(PROP_NAME, new JsonPrimitive(classPath));
return jo;
}
}