【问题标题】:Binary Serialization - replacing Marshal on scala 2.10二进制序列化 - 在 scala 2.10 上替换 Marshal
【发布时间】:2014-03-18 16:06:00
【问题描述】:

由于不推荐使用 scala.util.Marshal,我如何将这个旧代码迁移到 scala 2.10?

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,但它还没有发布。

【问题讨论】:

    标签: scala scala-2.10


    【解决方案1】:

    这是到目前为止提出的,实现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
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-09-12
      • 2012-09-17
      • 2013-04-04
      • 2016-09-16
      • 1970-01-01
      • 2013-06-19
      • 2014-01-04
      • 2012-10-08
      • 1970-01-01
      相关资源
      最近更新 更多