字段不完整时,用Circe解码Json [英] Decoding Json with Circe when fields are incomplete
问题描述
我有一个json格式的成绩单,里面有很多字
I have a transcript in json format with a bunch of words in it
{
"words": [{
"duration": 123,
"name": "world"
"time": 234,
"speaker": null
}]
}
我一直在使用Circe编码/解码Json.在这种情况下:
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)
我的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"之类的键,但很可能没有.否则,我会收到以下错误消息.
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?
推荐答案
正如Travis Brown在Gitter上指出的那样:
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
(加上para和import io.circe.generic.extras.auto._
的默认值)
(plus a default value for para and import io.circe.generic.extras.auto._
)
这篇关于字段不完整时,用Circe解码Json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!