Search code examples
scalacirceargonaut

Decoding Json with Circe when fields are incomplete


I have a transcript in json format with a bunch of words in it

{
     "words": [{
          "duration": 123,
          "name": "world"
          "time": 234,
          "speaker": null
      }]
}

I have been using Circe to encode/decode Json. In this particular case:

import io.circe.generic.auto._
import io.circe.parser._

val decoded = decode[Transcript](transcriptJson)

And my ADT look like:

case class Word(
  duration: Double,
  name: String,
  time: Float,
  para: String,
  speaker: Option[String],
  key: Option[String] = None,
  strike: Option[String] = None,
  highlight: Option[String] = None
)

case class Transcript(words: List[Word])

Sometimes words have keys like "strike" or "highlight", but most likely not. When it doesn't, I get the following error message.

Left(DecodingFailure([A]List[A], List(DownField(highlight), MoveRight, MoveRight, MoveRight, MoveRight, MoveRight, MoveRight, MoveRight, MoveRight, MoveRight, MoveRight, MoveRight, MoveRight, MoveRight, MoveRight, MoveRight, MoveRight, MoveRight, MoveRight, MoveRight, MoveRight, MoveRight, MoveRight, MoveRight, MoveRight, MoveRight, MoveRight, MoveRight, MoveRight, MoveRight, MoveRight, MoveRight, MoveRight, MoveRight, DownArray, DownField(words))))

What would be the best way to decode it properly when a "word" doesn't have all the fields?


Solution

  • As Travis Brown pointed out on Gitter:

    "this would work as-is with generic-extras:"

    import io.circe.generic.extras.Configuration
    
    implicit val config: Configuration = Configuration.default.withDefaults
    

    (plus a default value for para and import io.circe.generic.extras.auto._)