2
我有一個請求類如何使用Gson將json字符串轉換爲已知類型的數組?
class Request{
String serviceName ;
String methodName;
Serializable[] arguments;
}
這表示在服務器上執行的具體方法的請求。
參數是隨機完全可以serilizable的對象的數組。
現在我把它序列化使用
Request req = new Request("serviceName" , "methodName" , Serializable...)
// all arguments are specified through the elipsis and stored in the arguments array
Gson gson = new Gson() ;
gson.toJson(request) ;
現在我嘗試反序列化 - 的問題是顯而易見的,因爲GSON不知道類型的數組中的每個元素。
所以反序列化我有一個
Class<?>[] argTypes = new Class<?>[equalNumberToArguments]() ;
// This type array is filled with types that I know match the arguments array in request.
現在我有一個自定義解串器
class RequestDeserializer implements JsonDeserializer<Request> {
Class<?>[] paramTypes = null ;
// The types matching the arguments array are specified through the constructor here.
RequestDeserializer(Class<?>[] types){
paramTypes = types ;
}
@Override
public Request deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
final JsonObject jsonObject = json.getAsJsonObject();
String s = jsonObject.get("serviceName").getAsString();
String m = jsonObject.get("methodName").getAsString();
JsonElement element = jsonObject.get("arguments") ;
if (element.isJsonArray()){
JsonArray array = element.getAsJsonArray() ;
// - how do I implement retrieval of each json object from
array here ?
}
return null;
}
}