我正在编写一个rpc框架,但是面临有关序列化的问题。
您知道要在客户端和服务器之间转换请求,我应该有一个这样的Request类:
class Request {
// target service class
private Class<?> targetService;
// target service method
private String targetMethod;
// target method param types
private Class<?>[] targetParamTypes;
// the params
private Object[] targetParams;
// getters & setters & contructors
}
但是:
对于targetParams
字段,如果我将Gson用作序列化工具,则将POJO放入com.google.gson.internal.LinkedTreeMap cannot be cast to the.packages.to.MyClass
中会因一般问题而出现targetParams
错误。
对于int
类,Gson始终将其解析为Double
,所以我不能使用targetParamTypes[i].cast(targetParams[i])
强制将其强制转换为Integer(Double不能强制转换为Integer),糟透了...
那么有人有解决问题的办法吗?如何快速,准确地进行序列化/反序列化步骤?还是推荐任何工具?
我尝试过:
有什么建议吗?
答案 0 :(得分:3)
您可以看看Jackson。 Jackson的ObjectMapper
应该能够从您的Request
对象转换为String
,反之亦然。
编辑:添加了示例
请求实体:
class Request {
private Class<?> targetService;
private String targetMethod;
private Class<?>[] targetParamTypes;
private Object[] targetParams;
// needed by Jackson
private Request(){
}
public Request(Class<?> targetService,
String targetMethod,
Class<?>[] targetParamTypes,
Object[] targetParams) {
this.targetService = targetService;
this.targetMethod = targetMethod;
this.targetParamTypes = targetParamTypes;
this.targetParams = targetParams;
}
// getters and setters, needed by Jackson
}
序列化/反序列化示例:
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
Request req = new Request(String.class, "test", new Class[] {String.class}, new Object[] {"Test"});
String serialized = mapper.writeValueAsString(req);
System.out.println(serialized);
req = mapper.readValue(serialized, Request.class);
System.out.println(req);
}
答案 1 :(得分:0)
使用JSON代替GSON并在您的pojo中实现Serializable