2

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

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

我一直在使用 Circe 对 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))))

当“单词”没有所有字段时,正确解码它的最佳方法是什么?

4

1 回答 1

6

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

“这将与通用附加项按原样工作:”

import io.circe.generic.extras.Configuration

implicit val config: Configuration = Configuration.default.withDefaults

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

于 2017-09-28T17:38:44.567 回答