元组的Gzip序列,然后再次解压缩为元组序列 - 解压缩序列时出现

问题描述:

我有一个元组序列,需要gzip存储。之后,我希望能够提取压缩的内容,解压缩它,然后返回元组序列。元组的Gzip序列,然后再次解压缩为元组序列 - 解压缩序列时出现

我使用下面的代码进行解/压缩:

def unzip(x: Array[Byte]) : String = {  
    val inputStream = new GZIPInputStream(new ByteArrayInputStream(x)) 
    val output = scala.io.Source.fromInputStream(inputStream).mkString 
    return output 
} 

def gzip(input: Array[Byte]): Array[Byte] = { 
    val bos = new ByteArrayOutputStream(input.length) 
    val gzip = new GZIPOutputStream(bos) 
    gzip.write(input) 
    gzip.close() 
    val compressed = bos.toByteArray 
    bos.close() 
    compressed 
} 

从该源https://gist.github.com/owainlewis/1e7d1e68a6818ee4d50e服用。

然后我的例行或多或少如下:

val arr = Seq(("a",1),("b",2)) 

val arr_bytes = arr.toString.getBytes 

val comp = compress(arr_bytes) 

val x = unzip(comp) 

的输出是下面的:

arr: Seq[(String, Int)] = List((a,1), (b,2)) 
arr_bytes: Array[Byte] = Array(76, 105, 115, 116, 40, 40, 97, 44, 49, 41, 44, 32, 40, 98, 44, 50, 41, 41) 
comp: Array[Byte] = Array(31, -117, 8, 0, 0, 0, 0, 0, 0, 0, -13, -55, 44, 46, -47, -48, 72, -44, 49, -44, -44, 81, -48, 72, -46, 49, -46, -44, 4, 0, 35, 120, 118, -118, 18, 0, 0, 0) 
x: String = List((a,1), (b,2)) 

问题是现在x为具有从上面的格式的字符串(以单词列表也包含在内)。

例如:

x.toList 
res174: List[Char] = List(L, i, s, t, (, (, a, ,, 1,), ,, , (, b, ,, 2,),)) 

我的问题是,我该如何解我的确切顺序背,或者我如何再作X到我以前的序列?

+0

你正在写一个字符串流,然后从流中读取一个字符串......然后是惊讶,你有弦? – Dima

+0

您是否测试过使用任何已知的可用序列化库序列化数据?例如,您可以使用Jackson Scala模块(https://github.com/FasterXML/jackson-module-scala)将序列化的对象映射回scala类。 – Miguel

+0

嘿米格尔,是的,这就是我最终做的和它的工作:) – Mnemosyne

解决它使用播放API JSON库存储在JSON对象的内容:

val arr = Json.toJson(Array(Json.obj("name"-> "Bran", "age" -> 13),Json.obj("name"-> "Jon", "age" -> 18))) 

val arr_bytes = arr.toString().getBytes 

val comp = compress(arr_bytes) 

val x= unzip(comp) 

val json = Json.parse(x)