Dynamic Schema & Deserialization with Protostuff

不打扰是莪最后的温柔 提交于 2019-12-13 02:01:44

问题


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());

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?


回答1:


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

First one requires protostuff-runtime. You should create wrapper class with one field of type 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.

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.

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



来源:https://stackoverflow.com/questions/33154297/dynamic-schema-deserialization-with-protostuff

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!