动态架构用原形反序列化 [英] Dynamic Schema & Deserialization with Protostuff

查看:93
本文介绍了动态架构用原形反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Protostuff尝试对没有protobuf源可用的几种不同类型的对象进行序列化/反序列化(这是服务器-服务器RPC方案)。序列化可以了,因为我知道要序列化的对象的类型并可以创建架构:

I'm using Protostuff in an attempt to serialize/deserialize objects of several different types for which no protobuf sources are available (it's a server-server RPC scenario). Serialization goes OK because I know the type of the object to serialize and can create the schema:

Schema schema = RuntimeSchema.getSchema(object.getClass());

现在,我使用 ProtobufIOUtil.toByteArray 和得到一个字节数组,然后将其传递给远程服务器。但是,我似乎无法在远程服务器中反序列化此字节数组,因为我无法为未知类型的对象创建架构。有什么办法可以克服这个问题,并且可以像使用Java的本机序列化一样使用Protostuff?

Now, I use ProtobufIOUtil.toByteArray and get a byte array which I then pass to a remote server. However, I can't seem to deserialize this byte array in the remote server because I have no way to create a schema for an object of "unknown" type. Is there any way I can get past this and use Protostuff in the same way I would use Java's native serialization?

推荐答案

有几个有共同想法的解决方案-将类的名称与数据一起序列化。

There are few solutions with common idea - serialize name of the class together with the data.

第一个需要 protostuff-runtime 。您应该使用一个类型为 Object 的字段创建包装器类:

First one requires protostuff-runtime. You should create wrapper class with one field of type Object:

public class Wrapper {
    public Object data;
}

然后将对象放入 data 字段和序列化包装器, protostuff-runtime 会自动将类名附加到序列化表单中,然后再用于反序列化。

Then you put your object to data field and serialize wrapper, protostuff-runtime will append class name to serialized form automatically, and later use it for deserialization.

如果您想要更多控制权,那么可以在没有 protistuff运行时的情况下执行类似的操作。

If you want more control, then you can do similar thing without protistuff-runtime.

首先,您需要一个包装器类:

First, you need a wrapper class:

public class Wrapper {
    public String clazz;
    public byte[] data;
}

然后您应该将数据序列化为字节数组,将其存储到包装器,然后然后对包装实例进行序列化。

Then you should serialize your data to byte array, store it to wrapper, and then serialize wrapper instance.

在远程,首先对 Wrapper 进行反序列化,然后得到 clazz 字段-这是用于反序列化 data 的类。

On remote side, you deserialize Wrapper first, then get clazz field - it is the class you should use to deserialize data.

这篇关于动态架构用原形反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆