二进制序列化 - 替换scala 2.10上的Marshal

时间:2014-03-18 16:06:01

标签: scala scala-2.10

如何将此旧代码迁移到scala 2.10,因为不推荐使用scala.util.Marshal?

object Serilaizer{
 def objectToBytes[T](foo: T)(implicit expected: ClassManifest[T]): Array[Byte] = {
    Marshal.dump(foo)
  }
  def bytesToObject[T](fooBytes: Array[Byte])(implicit expected: ClassManifest[T]): Option[T] = {
    Some(Marshal.load[T](fooBytes))
    }
  }

我看到SBinary但尚未发布。

1 个答案:

答案 0 :(得分:0)

到目前为止,这是实现original Marshal dump/load代码(如scala 2.9),不确定这是最好的方法,但它似乎正在工作

object Serilaizer {
  def objectToBytes[T](foo: T): Array[Byte] = { // replace Marshal.dump(foo)
    val ba = new ByteArrayOutputStream()
    val out = new ObjectOutputStream(ba)
    out.writeObject(foo)
    out.close()
    ba.toByteArray
  }

  def bytesToObject[T](fooBytes: Array[Byte]): Option[T] = { // replace Marshal.load[T](foo)
    if (userDataBytes != null) {
      try {
        val in = new ObjectInputStream(new ByteArrayInputStream(fooBytes))
        val o = in.readObject.asInstanceOf[T]
        in.close()
        Some(o)
      }
      catch {
        case e: Exception => {
          throw new ClassCastException ("Serialization Problem", e)
          None
        }
      }
    }
    else {
      None
    }
  }
}