簡體   English   中英

字段不完整時,用Circe解碼Json

[英]Decoding Json with Circe when fields are incomplete

我有一個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))))

當“單詞”沒有所有字段時,正確解碼它的最佳方法是什么?

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

“這可以與通用擴展一起使用:”

import io.circe.generic.extras.Configuration

implicit val config: Configuration = Configuration.default.withDefaults

(加上para的默認值並import io.circe.generic.extras.auto._

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM