Search code examples
scalacirce

Is there a way to have optional fields in a Circe decoder?


I have a case class on which every field is optional, like:

case class Foo(name: Option[String],
               phone: Option[String],
               email: Option[String])

I was trying to create a manual Decoder for my case class and found that a decoder is something like:

implicit val decoder: Decoder[Foo] = (c: HCursor) => {
  for {
    name <- c.downField("name").as[String]
    phone <- c.downField("phone").as[String]
    email <- c.downField("email").as[String]
  } yield {
    new Foo(name, phone, email)
  }
}

But checking downField method, if the field is not set, the cursor will chage to FailedCursor, so an error will rise.

How can I expect some field to be optional and return None if it is not defined?


Solution

  • Just use c.downField.as[Option[T]], so your code will be like this:

    implicit val decoder: Decoder[Foo] = (c: HCursor) => {
      for {
        name <- c.downField("name").as[Option[String]]
        phone <- c.downField("phone").as[Option[String]]
        email <- c.downField("email").as[Option[String]]
      } yield new Foo(name, phone, email)
    }