Search code examples
scalacircehttp4s-circe

Need help decoding following json with Circe


I'm trying to parse nested JSON object with Circe library. I would like to map it to flat case class ignoring some of the fields.

import io.circe.generic.auto._
import io.circe.{Decoder, Encoder, HCursor, Json}

val jsonString = """{
  "parent" : {
    "name" : "title",
    "items" : [
      {
        "foo" : "",
        "attrs" : {
          "attrA" : "",
          "attrB" : ""
        }
      },
      {
        "foo" : "",
        "attrs" : {
          "attrA" : "",
          "attrB" : "",
          "attrC" : ""
        }
      }]
    }
}"""


// Notice I don't care about "attrC"
case class Item(foo: String, attrA: String, attrB: String)
case class Parent(name: String, items: List[Item])

implicit val testDecoder: Decoder[Item] = Decoder.instance { c =>
    val itemsC = c.downField("parent").downField("items")

    for {
      foo <- itemsC.get[String]("foo")
      a <- itemsC.downField("attrs").get[String]("attrA")
      b <- itemsC.downField("attrs").get[String]("attrB")
    } yield Item(foo, a, b)
  }

val decodingResult = parser.decode[Parent](jsonString)

result: Either[io.circe.Error,Parent] = Left(DecodingFailure(Attempt to decode value on failed cursor, List(DownField(name))))


Solution

  • I find it easier to use the auto-parser, get the data to Scala, and continue from there

    import io.circe.generic.auto._
    import io.circe.parser._
    
    val sample="""{
      "parent" : {
        "name" : "title",
        "items" : [
          {
            "foo" : "",
            "attrs" : {
              "attrA" : "",
              "attrB" : ""
            }
          },
          {
            "foo" : "",
            "attrs" : {
              "attrA" : "",
              "attrB" : "",
              "attrC" : ""
            }
          }
          ]
        }
      }"""
    
    
    case class Data(parent : Parent)
    case class Parent(name: String, items: List[Item])
    case class Item(foo: String, attrs : Attrs)
    case class Attrs(attrA: String, attrB: String) // you don't need attributes you don't use
    val data=decode[Data](sample)