二进制序列化 - 在 Scala 2.10 上替换 Marshal [英] Binary Serialization - replacing Marshal on scala 2.10
本文介绍了二进制序列化 - 在 Scala 2.10 上替换 Marshal的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
由于不推荐使用 scala.util.Marshal,我该如何将旧代码迁移到 scala 2.10?
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))
}
}
我看到了 SBinary 但它还没有发布.
I saw SBinary but it is not released yet.
推荐答案
这是迄今为止的一个想法,实现了 原始 Marshal 转储/加载 代码(如在 scala 2.9 中),不确定这是最好的方法,但它似乎有效 >
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
}
}
}
这篇关于二进制序列化 - 在 Scala 2.10 上替换 Marshal的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文