简体   繁体   English

Scala 多层隐式读写 map

[英]Scala implicit read and write for multi layered map

I have defined a multi-layered map:我已经定义了一个多层 map:

import collection.mutable.Map
var modelsRef = Map[String,Map[String,Array[String]]]()

and filled it with data;并用数据填充它; for example by using:例如通过使用:

myMap.update("a", Map("b1" -> Array("c","d","e","f")))
myMap("a").update("b2", Array("g","h"))

I'd like to write the result in a json file and later read it from the file and re-built the map structure.我想将结果写入json文件,然后从文件中读取并重新构建 map 结构。 I am using the maven Scala and I am thinking to use the Play or an equivalent package.我正在使用 maven Scala 并且我正在考虑使用Play或等效的 package。 I read in other posts that I need to define a case class and then write an implicit Writer and Reader .我在其他帖子中读到我需要定义一个case class ,然后编写一个implicit Writer and Reader I appreciate it if anyone can show me what it may look like for such a complicated multi-layered map?如果有人能告诉我这样复杂的多层 map 的外观,我将不胜感激?

You don't need to define any special case class as most of json libraries support "base" types like Map, String, Array, etc by default.您不需要定义任何特殊情况 class 因为大多数 json 库默认支持“基本”类型,如 Map、字符串、数组等。

Example done with circe .circe完成的示例。

  import scala.collection.mutable
  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 = map.asJson.pretty(Printer.noSpaces)

  println(json)
  // {"a":{"b2":["g","h"],"b1":["c","d","e","f"]}}
  println(decode[Map[String, Map[String, Seq[String]]]](json))
  // Right(Map(a -> Map(b2 -> List(g, h), b1 -> List(c, d, e, f))))

Notice that you aren't required to use mutable collections to read the json back into structure.请注意,您不需要使用可变 collections 将 json 读回结构。 In my example, I used immutable collections in decode method.在我的示例中,我在decode方法中使用了不可变的 collections。

Update :更新

I tested the above code with Scala 2.12.8 and circe 0.11.2.我用 Scala 2.12.8 和大约 0.11.2 测试了上面的代码。 Dependencies for maven are maven 的依赖项是

<dependency>
    <groupId>io.circe</groupId>
    <artifactId>circe-core_2.12</artifactId>
    <version>0.11.2</version>
</dependency>
<dependency>
    <groupId>io.circe</groupId>
    <artifactId>circe-parser_2.12</artifactId>
    <version>0.11.2</version>
</dependency>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM