Decoding Json with Circe when fields are incomplete

僤鯓⒐⒋嵵緔 提交于 2019-12-24 01:29:11

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/46474517/decoding-json-with-circe-when-fields-are-incomplete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!