使用circe将Map [String,MyCaseClass]编码为Seq [String,String]

时间:2018-07-17 09:53:24

标签: scala circe

根据问题,如何使用circe将Map [String,MyCaseClass]编码为Seq [String,String]?

型号:

case class MyCaseClass(name: String, enabled: Boolean)

case class Parent(parentName: String,
                  collection: Map[String, MyCaseClass])

Parent(
    "parent-name",
    Map(
        "external-name-a", MyCaseClass("internal-name-a", true),
        "external-name-b", MyCaseClass("internal-name-b", false)
    )
 )

我想将此编码为:

Seq[name = <map key>, enabled = <boolean value from MyCaseClass>]

例如:

    { ...
      collection: [
      {
        name: "external-name-a",
        enabled: true
      },
      {
        name: "external-name-a",
        enabled: false
      }
    ]
  ...
  }

我了解了以下内容,只是不确定该怎么做

object Parent {

  implicit val encodeParent: Encoder[Parent] = (parent: Parent) => {
    Json.obj(
      ("name", parent.name.asJson),
      ("collection", parent.collection.asJson),
    )
  }

  implicit val encodeCollection: Encoder[Map[String, MyCaseClass]] = (collection: Map[String, MyCaseClass]) => {

    //collection.toList.map((externalName: String, myCaseClass: MyCaseClass) => (externalName, myCaseClass.enabled)).asJson
  }
}

1 个答案:

答案 0 :(得分:0)

这有效:

implicit val encodeCollection: Encoder[Map[String, MyCaseClass]] = (collection: Map[String, MyCaseClass]) => {

    collection.toList.
      map(collection => (collection._1, collection._2.enabled)).
      map(collection => Json.obj(
        ("name", collection._1.asJson),
        ("enabled", collection._2.asJson)
      )).asJson
  }