问题
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