Scala - 将 Json 对象写入文件并读取它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17521364/
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-09-03 19:55:35  来源:igfitidea点击:

Scala - Writing Json object to file and reading it

jsonscalaparsing

提问by yAsH

I have a Map like below

我有一张像下面这样的地图

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"]}]
)

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

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

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

Am able to read the Json string from the file using

能够使用从文件中读取 Json 字符串

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

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

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

EDIT:Am able to read the map with

编辑:我能够阅读地图

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.

但是,随着地图大小的增加,这个过程需要更多的时间。

采纳答案by Bruno Grieder

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

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

I would recommend using HymansMapperwhich wraps the excellent Hymansonfor a more pleasant Scala usage.

我会推荐使用HymansMapper,它包装了优秀的Hymanson以获得更愉快的 Scala 使用。

Serializing to JSON becomes as simple as

序列化为 JSON 变得如此简单

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

... and deserializing

...和反序列化

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

(edit)

(编辑)

You can make also writing and reading simple one-liners using FileUtils from commons-iodoing

您可以同时写入和读取使用简单的单行文件实用程序从公共-IO

val json = FileUtils readFileToString (file, encoding)

and

FileUtils write (file, json, encoding) 

回答by Greg

I actually got a lot more use from json4s. The documentation is much more clear and comprehensive, and the usage seems slightly easier.

我实际上从json4s得到了更多的使用。文档更加清晰和全面,使用起来似乎稍微容易一些。

A similar operation to the one you are requesting would look like this

与您请求的操作类似的操作如下所示

import org.json4s.native.JsonFormats.parse

... get your json string ...
val parsedJson = parse(json)
val extractedJson = parsedJson.extract[MyClass]