【发布时间】:2016-06-20 18:16:17
【问题描述】:
我有一个请求类
class Request{
String serviceName ;
String methodName;
Serializable[] arguments;
}
这表示在服务器上执行特定方法的请求。
参数是一个随机的完全可序列化对象的数组。
现在我使用
对其进行序列化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;
}
}
【问题讨论】:
标签: java arrays json gson deserialization