【问题标题】:Scala convert multi-layered json to multi-layered mapScala将多层json转换为多层map
【发布时间】:2020-03-17 23:28:24
【问题描述】:

我有一张多层地图:

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 格式,我将不胜感激。

【问题讨论】:

    标签: json scala dictionary circe


    【解决方案1】:

    我找到了答案:

    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
    

    【讨论】:

      猜你喜欢
      • 2017-03-20
      • 2019-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-06
      • 1970-01-01
      相关资源
      最近更新 更多