猿问

如何正确序列化/反序列化 Java Object[]?

我正在编写一个 rpc 框架,但面临有关序列化的问题。


你知道在客户端和服务器之间转换请求,我应该有一个这样的请求类:


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

}

但:

  1. 对于该targetParams领域,如果我使用 Gson 作为序列化工具,com.google.gson.internal.LinkedTreeMap cannot be cast to the.packages.to.MyClass如果我将 POJO 放入 中targetParams,对于通用问题,它会出错。

  2. 对于int类,Gson 总是将其解析为 a Double,所以我不能使用targetParamTypes[i].cast(targetParams[i])强制将其强制转换为 Integer(Double 不能转换为 Integer),它很糟糕...

那么有人有解决问题的方法吗?如何使序列化/反序列化步骤快速准确?或者有什么推荐的工具吗?

我努力了:

  • Gson,之前遇到的问题

  • Kyro,编解码器系统很烂,我不知道如何序列化/反序列化 HashMap ......

  • protostuff,嗯,它不支持 Java 9+,我的环境是 Java 11,糟糕!

所以有什么建议吗?


慕妹3146593
浏览 187回答 2
2回答

qq_遁去的一_1

你可以看看杰克逊。Jackson'sObjectMapper应该能够从您的Request对象转换为String,反之亦然。编辑:添加示例请求实体:class Request {&nbsp; &nbsp; private Class<?> targetService;&nbsp; &nbsp; private String targetMethod;&nbsp; &nbsp; private Class<?>[] targetParamTypes;&nbsp; &nbsp; private Object[] targetParams;&nbsp; &nbsp; // needed by Jackson&nbsp; &nbsp; private Request(){&nbsp; &nbsp; }&nbsp; &nbsp; public Request(Class<?> targetService,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;String targetMethod,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Class<?>[] targetParamTypes,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Object[] targetParams) {&nbsp; &nbsp; &nbsp; &nbsp; this.targetService = targetService;&nbsp; &nbsp; &nbsp; &nbsp; this.targetMethod = targetMethod;&nbsp; &nbsp; &nbsp; &nbsp; this.targetParamTypes = targetParamTypes;&nbsp; &nbsp; &nbsp; &nbsp; this.targetParams = targetParams;&nbsp; &nbsp; }&nbsp; &nbsp; // getters and setters, needed by Jackson}序列化/反序列化示例:public static void main(String[] args) throws IOException {&nbsp; &nbsp; ObjectMapper mapper = new ObjectMapper();&nbsp; &nbsp; Request req = new Request(String.class, "test", new Class[] {String.class}, new Object[] {"Test"});&nbsp; &nbsp; String serialized = mapper.writeValueAsString(req);&nbsp; &nbsp; System.out.println(serialized);&nbsp; &nbsp; req = mapper.readValue(serialized, Request.class);&nbsp; &nbsp; System.out.println(req);}

月关宝盒

使用 JSON 而不是 GSON 并在你的 pojo 中实现 Serializable
随时随地看视频慕课网APP

相关分类

Java
我要回答