序列化与反序列化
Cruzr 系统运行过程中会处理大量的进程间通讯,随之而来的是频繁的数据序列化与反序列化。 为了简化开发者的数据序列化处理, Cruzr 系统抽象出 Marshaller 接口, 专门处理数据序列化与反序列化。
抽象接口
- Marshaller
将原始数据序列化为 byte[] 的操作由 marshall 函数完成, 将 byte[] 反序列化为原始数据的操作由 unmarshall 函数完成, 具体如下:
public interface Marshaller { <T> T unmarshall(byte[] value, Type type) throws IOException; byte[] marshall(Object value) throws IOException; }
- MarshallerFactory
public interface MarshallerFactory { Marshaller create(); String contentType(); }
注:
MarshallerFactory用于创建指定类型Marshaller, Cruzr 系统默认提供了常用的Marshaller实现,开发者也可以根据需要创建自定义类型的Marshaller
数据类型
Cruzr 系统提供了常见的三种数据类型的 Marshaller 实现:
- PARCELABLE
ParcelableMarshaller 用于处理 Android Parcelable 数据类型的序列化与反序列化操作, 通过 ParcelableMarshallerFactory 创建
public void testMarshaller() throws IOException { Marshaller marshaller = new ParcelableMarshallerFactory().create(); Bundle parcelable = createYourValue(); byte[] bytes = marshaller.marshall(parcelable); parcelable = marshaller.unmarshall(bytes, Bundle.class); }
- PROTOBUF
ProtobufMarshaller 用于处理 Protobuf 数据类型的序列化与反序列化操作, 通过 ProtobufMarshallerFactory 创建
public void testMarshaller() throws IOException { Marshaller marshaller = new ProtobufMarshallerFactory().create(); ProtoClass protobuf = createYourValue(); byte[] bytes = marshaller.marshall(protobuf); protobuf = marshaller.unmarshall(bytes, ProtoClass.class); }
- JSON
GsonMarshaller 用于处理普通类型的序列化与反序列化操作, 通过 GsonMarshallerFactory 创建
public void testMarshaller() throws IOException { Marshaller marshaller = new GsonMarshallerFactory().create(); NormalClass normal = createYourValue(); byte[] bytes = marshaller.marshall(normal); normal = marshaller.unmarshall(bytes, NormalClass.class); }
注:以上反序列化操作的原始数据类型
xxx.class必须与序列化数据的原始类型一致才能正确使用。以上类型的常量参数定义在
com.ubtrobot.marshall.ContentTypes
使用方式
Cruzr 系统自带 PARCELABLE 类型的序列化与反序列化实现, 其他类型或者用户自定义类型, 可以通过以下方式添加到 Cruzr 系统中:
// add JSON marshaller Master.get().addMarshallerFactory(new GsonMarshallerFactory()); // add custom marshaller Master.get().addMarshallerFactory(new CustomMarshallerFactory());
- 序列化使用
在 Cruzr 系统中使用序列化操作集中在发送指令和发布事件,下面以发布事件为例说明:
// publish interface void publish(String topic, Object parameterObj, String contentType); //demo code robotContext.publish("event.action.power.BATTERY_CHANGE", batteryProperties, ContentTypes.PARCELABLE);
注:序列化参数大小不能超过 1 MB.
发布事件序列化操作只需要填写序列化原始数据 parameterObj 以及 指定序列化类型参数 contentType 即可, 发送指令过程的序列化操作同理。
- 反序列化使用
在 Cruzr 系统中反序列化已经替开发者完成了, 只要添加好对应类型的 Marshaller 到 Cruzr 系统内, 在需要反序列化的时候,系统会自动完成。