Scala 将多层 json 转换为多层地图

Scala convert multi-layered json to multi-layered map

我有一张多层地图:

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 代码并重新生成地图变量。我尝试了以下选项:

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)
其中

None 是我原来的 HashMap 形式。如果您能告诉我如何将其转换为原始 map 格式,我将不胜感激。

我找到了答案:

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.get