我有一个多层地图:
import scala.io.Source
import scala.collection.mutable
import io.circe.Printer
import io.circe.parser._
import io.circe.syntax._
var map = mutable.Map[String, mutable.Map[String, mutable.ArrayBuffer[String]]]()
map.update("a", mutable.Map("b1" -> mutable.ArrayBuffer("c", "d", "e", "f")))
map("a").update("b2", mutable.ArrayBuffer("g", "h"))并将其保存在文件中:
val json_path = "C:/myjason.json"
val json = map.asJson.pretty(Printer.spaces2)
var w: Writer = new FileWriter(json_path,false)
w.write(json)
w.close()现在,我正在尝试将文件读回到我的scala代码中,并重新生成map变量。我尝试了以下选项:
val json1 = Source.fromFile(json_path).getLines.mkString
val json2 = parse(json1.toString)
val json3 = decode[mutable.Map[String, mutable.Map[String, ArrayBuffer[String]]]](json2.toString)我得到的是:
json1 is a string of "{"a" : {"b1" : ["c","d","e","f"], "b2" : ["g","h"]}}"
json2 is Right({"a" : {"b1" : ["c","d","e","f"], "b2" : ["g","h"]}})
json3 is io.circe.ParsingFailure: expected json value got 'Right(...' (line 1, column 1)这些都不是我最初使用的HashMap格式。如果你能建议我如何将它转换成原始的map格式,我将不胜感激。
发布于 2019-11-23 08:00:56
我找到了答案:
val json = Source.fromFile(json_path).getLines.mkString
val decoded_json = decode[mutable.Map[String, mutable.Map[String, ArrayBuffer[String]]]](json.toString)
val map = decoded_json.right.gethttps://stackoverflow.com/questions/58984960
复制相似问题