在字段不完整时使用 Circe 解码 Json

Decoding Json with Circe when fields are incomplete

我有一份 json 格式的成绩单,里面有一堆单词

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

我一直在使用 Circe 来 encode/decode Json。在这种特殊情况下:

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

val decoded = decode[Transcript](transcriptJson)

我的 ADT 看起来像:

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

有时单词有 "strike" 或 "highlight" 之类的键,但很可能没有。如果没有,我会收到以下错误消息。

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

当 "word" 没有所有字段时,正确解码的最佳方法是什么?

正如 Travis Brown 在 Gitter 上指出的那样:

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

import io.circe.generic.extras.Configuration

implicit val config: Configuration = Configuration.default.withDefaults

(加上 para 和 import io.circe.generic.extras.auto._ 的默认值)