简体   繁体   English

具有原型的动态架构和反序列化

[英]Dynamic Schema & Deserialization with Protostuff

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). 我正在使用Protostuff,尝试对没有protobuf源可用的几种不同类型的对象进行序列化/反序列化(这是服务器-服务器RPC方案)。 Serialization goes OK because I know the type of the object to serialize and can create the schema: 序列化可以,因为我知道要序列化的对象的类型并可以创建模式:

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

Now, I use ProtobufIOUtil.toByteArray and get a byte array which I then pass to a remote server. 现在,我使用ProtobufIOUtil.toByteArray并获取一个字节数组,然后将其传递给远程服务器。 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? 有什么方法可以克服这个问题,并且可以像使用Java本机序列化一样使用Protostuff?

There are few solutions with common idea - serialize name of the class together with the data. 很少有具有共同思想的解决方案-将类的名称与数据一起序列化。

First one requires protostuff-runtime . 第一个需要protostuff-runtime You should create wrapper class with one field of type Object : 您应该使用Object类型的一个字段创建包装器类:

public class Wrapper {
    public Object data;
}

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. 然后,将您的对象放入data字段并序列化包装器, protostuff-runtime将自动将类名附加到序列化的表单中,然后将其用于反序列化。

If you want more control, then you can do similar thing without protistuff-runtime . 如果您需要更多控制权,那么可以在没有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. 然后,您应该将数据序列化为字节数组,将其存储到包装器,然后序列化包装器实例。

On remote side, you deserialize Wrapper first, then get clazz field - it is the class you should use to deserialize data . 在远程方面,您首先要对Wrapper反序列化,然后获得clazz字段-这是您应该对data进行反序列化的类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM