scala 将Scala中的任何类型转换为Array[Byte]并返回

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39369319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 08:36:58  来源:igfitidea点击:

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

scalaserialization

提问by Ectoras

I have the following question:

我有以下问题:

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

我的程序中有一个变量值,它被声明为 Any 值。

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.

如何序列化到字节数组并返回?我找到了与其他类型相关的示例,例如 Double 或 Int,但不是 Any。

回答by Bruce Lowe

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

这应该做你需要的。这与人们在 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)))
}

回答by Ectoras

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
  }