这个代码包括了 int数组,对象的序列化和反序列化。

 

Serial是由Twitter高性能序列化方案,它力求帮助开发者实现高性能和高可控的序列化过程。
GitHub:​​​https://github.com/twitter/Serial/blob/master/README-CHINESE.rst/​

Serial方案的主要优点如下:

  • 相比起传统的反射序列化方案更加高效(没有使用反射)
  • 性能相比传统方案提升了3倍 (序列化的速度提升了5倍,反序列化提升了2.5倍)
  • 序列化生成的数据量(byte[])大约是之前的1/5
  • 开发者对于序列化过程的控制较强,可定义哪些object、field需要被序列化
  • 有很强的debug能力,可以调试序列化的过程(详见:​​调试​​)
/**
* @author Administrator
* @date 2020/7/20
*/
public class Person {
String name;
int age;
int[] arr;
Color c;

public Person(String name, int age, int[] arr,Color c) {
this.name = name;
this.age = age;
this.arr = arr;
this.c = c;
}

// 需要单独定义一个序列化操作相关的变量
public static final ObjectSerializer<Person> SERIALIZER = new PersonSerializer();

// 实际用来定义序列化和解序列化的操作,类似Parcelable的Creator
private static final class PersonSerializer extends ObjectSerializer<Person> {
@Override
protected void serializeObject(SerializationContext context,
SerializerOutput output,
Person object) throws IOException {
// 第三个参数地址指向要序列化类,通过第二个参数output进行序列化
output.writeString(object.name);
output.writeInt(object.age);
for (int i = 0; i < object.arr.length; i++) {
output.writeInt(object.arr[i]);
}
output.writeString(object.c.red);
output.writeString(object.c.green);
output.writeString(object.c.blue);
// output.writeObjectStart()

}

@Override
protected Person deserializeObject(SerializationContext context,
SerializerInput input,
int versionNumber) throws IOException {
// versionNumber 为版本号,控制版本信息。具体只要在
// public static final ObjectSerializer<People> SERIALIZER = new PeopleSerializer(1);
// 构造函数添加版本号即可,就可通过versionNumber进行控制版本
String name = input.readString();
int age = input.readInt();
int[] arr = new int[3];
for (int i = 0; i < arr.length; i++) {
arr[i] = input.readInt();
}
String r = input.readString();
String g = input.readString();
String b = input.readString();


return new Person(name, age, arr,new Color(r,g,b));
}
}
}
public class Color {
String red;
String green;
String blue;

public Color(String red, String green, String blue) {
this.red = red;
this.green = green;
this.blue = blue;
}
}
Person person = new Person(str, 23, new int[]{2, 3, 4},new Color("z","d","s"));
final Serial serial = new ByteBufferSerial();
try {
final byte[] serializedData = serial.toByteArray(person, person.SERIALIZER);
Log.i("serial", serializedData.length + "");

Person output = serial.fromByteArray(serializedData, Person.SERIALIZER);
Log.i("Serial", "name : " + output.name + " ; age : " + output.age + " " + output.arr[2] +" " + output.c.red);
} catch (Exception e) {
e.printStackTrace();
}