Scala-将Json对象写入文件并读取 [英] Scala - Writing Json object to file and reading it

查看:1150
本文介绍了Scala-将Json对象写入文件并读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的地图

val map : scala.collection.mutable.Map[String,Any] = Map(
  dummy1 -> ["cat1", "hash1", 101, 1373269076, {"1" : ["dummy", "dummy", "dummy"]}],
  dummy2 -> ["cat1", "hash1", 102, 1373269076, {"2" : ["dummy", "dummy", "dummy"]}],
  dummy3 -> ["cat1", "hash1", 103, 1373269076, {"3" : ["dummy", "dummy", "dummy"]}]
)

我将其转换为Json字符串,然后使用以下代码将其写入文件中

I converted it into a Json string and then wrote it into a file with the code below

Some(new PrintWriter("foo.txt")).foreach{p =>
  p.write(JSONObject(map.toMap).toString()); p.close
}

能够使用

val json_string = scala.io.Source.fromFile("foo.txt").getLines.mkString

如何从上面的Json字符串取回地图?

How do I get my map back from the Json string above?

编辑:能够使用

val map1 = JSON.parseFull(json_string).get.asInstanceOf[Map[String,Any]]

但是,随着地图尺寸的增加,此过程将花费更多时间.

But, this process is taking more time as the size of the map increases.

推荐答案

尝试使用可能更快(更彻底)的映射器.

Try using a likely faster (and more thorough) mapper.

我建议使用 JacksMapper ,它包装了出色的

I would recommend using JacksMapper which wraps the excellent Jackson for a more pleasant Scala usage.

序列化为JSON就像

val json = JacksMapper.writeValueAsString[MyClass](instance)

...反序列化

val obj = JacksMapper.readValue[MyClass](json)

(编辑)

您还可以使用 commons-io的FileUtils 在做

val json = FileUtils readFileToString (file, encoding)

FileUtils write (file, json, encoding) 

这篇关于Scala-将Json对象写入文件并读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆