我沒有找到這種RPC機制,但我設法使用JSON來處理這個。我發現Gson是在Java中使用JSON的谷歌API。它將對象轉換爲可以被解釋爲字符串的JsonElements,反之亦然。因此,幫助我開發這一功能的關鍵特性是Gson的定製串行器/解串器。我實現了一個類,這是串行器和解串爲對象,我爲源類以及類的內容發送類名:
class MySerializerAndDeserializer implements JsonSerializer<Object>, JsonDeserializer<Object>{
public JsonElement serialize(Object src, Type typeOfSrc,
JsonSerializationContext context) {
Class clazz = src.getClass();
JsonElement serialize = context.serialize(src);
JsonArray array = new JsonArray();
array.add(new JsonPrimitive(clazz.getName()));
array.add(serialize);
return array;
}
public Object deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
JsonArray array = json.getAsJsonArray();
String asString = array.get(0).getAsString();
Object deserialize = null;
try {
deserialize = context.deserialize(array.get(1).getAsJsonObject(), Class.forName(asString));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return deserialize;
}
}
,然後我註冊MySerializerAndDeserializer爲Parent.class:
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Parent.class, new MySerializerAndDeserializer());
最後用GSON,得到了我正確的預期實例:
String json = gson.toJson(container, Container.class);
Container containerFromJson = gson.fromJson(json, Container.class);