[关闭]
@xtccc 2017-08-21T23:41:19.000000Z 字数 1888 阅读 1715

Serialization / Deserialization

给我写信
GitHub

此处输入图片的描述

Scala


有一篇比较各种库性能的文章:
Scala Serialization

pickling


参考:

pickling是最方便的序列化库,可以直接支持大部分的Scala数据类型。

基本用例

  1. import scala.pickling.Defaults._
  2. import scala.pickling.binary._
  3. val d = new DateTime()
  4. val pckl = d.pickle
  5. val bytes = pckl.value // 序列化成字节
  6. println(s"bytes length = ${bytes.length}")
  7. val obj = BinaryPickle(bytes).unpickle[DateTime]
  8. println(s"obj = $obj") // 从字节数组反序列化回来


Customized Picker/Unpicker

先看个最基本的case class的pickler/unpickler

  1. import scala.pickling.tags.FastTypeTag
  2. import scala.pickling.binary._
  3. import scala.pickling.Defaults._
  4. import scala.pickling._
  5. case class Foo(val x: String, y: Int, z: String)
  6. object CustomerPicklerUnpicklers {
  7. implicit object FooPickler extends AbstractPicklerUnpickler[Foo] {
  8. // 不需要写 stringPickler,写了的话会报错, 以为已经存在PrimitivePicklers.stringPickler
  9. val stringUnpickler = implicitly[Unpickler[String]] // 但是不存在stringUnpickler
  10. val intUnpickler = implicitly[Unpickler[Int]]
  11. override val tag = FastTypeTag[Foo]
  12. override def pickle(foo: Foo, builder: PBuilder): Unit = {
  13. println(s"Pickling Foo ...")
  14. builder.beginEntry(foo, tag)
  15. builder.putField("x", b => stringPickler.pickle(foo.x , b))
  16. builder.putField("y", b => intPickler.pickle(foo.y , b))
  17. builder.putField("z", b => stringPickler.pickle(foo.z , b))
  18. builder.endEntry()
  19. }
  20. override def unpickle(tag: String, reader: PReader): Foo = {
  21. println("Unpickling Foo ...")
  22. val x = stringUnpickler.unpickleEntry(reader.readField("x")).asInstanceOf[String]
  23. val y = intUnpickler.unpickleEntry(reader.readField("y")).asInstanceOf[Int]
  24. val z = stringUnpickler.unpickleEntry(reader.readField("z")).asInstanceOf[String]
  25. Foo(x, y, z)
  26. }
  27. }
  28. }
  29. object TestFoo {
  30. import CustomerPicklerUnpicklers._
  31. def main(args: Array[String]): Unit = {
  32. val foo = Foo("Hello", 100, null) // 支持null
  33. val pckl = foo.pickle
  34. val bytes = pckl.value
  35. println(s"length = ${bytes.length}")
  36. val obj = BinaryPickle(bytes).unpickle[Foo]
  37. println(obj)
  38. }
  39. }

输出为

Pickling Foo ...
length = 79
Unpickling Foo ...
Foo(Hello,100,null)


添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注