Encode Map[String, MyCaseClass] into Seq[String, String] using circe

随声附和 提交于 2019-12-25 01:53:47

问题


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
  }


来源:https://stackoverflow.com/questions/51378340/encode-mapstring-mycaseclass-into-seqstring-string-using-circe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!