Convert Any type in scala to Array[Byte] and back

匿名 (未验证) 提交于 2019-12-03 02:52:02

问题:

I have the following question:

I have a variable value in my program which is declared as Any value.

I want to convert this value to Byte Array..

How can I serialize to byte Array and back? I found examples related to other types such as Double or Int, but not as Any.

回答1:

This should do what you need. It's pretty similar to how one would do it in Java.

import java.io.{ByteArrayInputStream, ByteArrayOutputStream, ObjectInputStream, ObjectOutputStream}  object Serialization extends App {    def serialise(value: Any): Array[Byte] = {     val stream: ByteArrayOutputStream = new ByteArrayOutputStream()     val oos = new ObjectOutputStream(stream)     oos.writeObject(value)     oos.close     stream.toByteArray   }    def deserialise(bytes: Array[Byte]): Any = {     val ois = new ObjectInputStream(new ByteArrayInputStream(bytes))     val value = ois.readObject     ois.close     value   }    println(deserialise(serialise("My Test")))   println(deserialise(serialise(List(1))))   println(deserialise(serialise(Map(1 -> 2))))   println(deserialise(serialise(1))) } 


回答2:

def anyTypeToByteArray(value: Any): Array[Byte] = {     val valueConverted :Array[Byte] = SerializationUtils.serialize(value.isInstanceOf[Serializable])     valueConverted   }    def ByteArrayToAny(value: Array[Byte]): Any = {     val valueConverted: Any = SerializationUtils.deserialize(value)     valueConverted   } 


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