Encode Map[String, MyCaseClass] into Seq[String, S

2019-08-28 00:19发布

问题:

As per the question, how to encode Map[String, MyCaseClass] into Seq[String, String] using circe?

Model:

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

I'd like to encode this into a:

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

For example:

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

I got as far as the following, just unsure exactly how to do what I want

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:

This works:

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
  }


标签: scala circe