Binary Serialization - replacing Marshal on scala 2.10

夙愿已清 提交于 2019-12-07 04:02:55

问题


how can I migrate this old code to scala 2.10 since scala.util.Marshal is deprecated ?

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))
    }
  }

I saw SBinary but it is not released yet.


回答1:


this is what a came up with so far , implementing the original Marshal dump/load code (as in scala 2.9), not sure that this is the best way , but it seems to be working

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
    }
  }
}


来源:https://stackoverflow.com/questions/22484765/binary-serialization-replacing-marshal-on-scala-2-10

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!