我有我的Circe Decoder,如下所示。我相信我的情感解碼器可以正常作業,所以下面就不包括它了。
case class CryptoData(value。String, valueClassification: Sentiment)。
implicit val解碼器。Decoder[CryptoData] = Decoder.instance { json =>
for {
value <- json.downField("data").get[String]("value")
valueClassification <- json.downField("data").get[Sentiment] ("value_classification")
} yield CryptoData(value, valueClassification)
}
我的Json看起來像這樣
{
"name" : "Fear and greed Index"。
"data" : [
{
"value" : "31"。
"value_classification" : "Fear",
"timestamp" : "1631318400",
"time_until_update" : "54330".
}
],
"metadata"/span> : {
"error" : null
}
}
我只是想要value和value_classification。正如可以看到的,這些值位于一個陣列中。
我懷疑Circe正在尋找解碼一個List[data],但我不想創建一個case class DataInfo(list: List[Data]),它感覺不對。
uj5u.com熱心網友回復:
你只是錯過了一個downArray的呼叫來決議data作為物件的陣列。作業解碼器:
implicit val cryptoDecoder。Decoder[CryptoData] = Decoder.instance { json =>
val data = json.downField("data"/span>).downArray
for {
value <- data.get[String]("value")
valueClassification <- data.get[Sentiment]("value_classification")
} yield CryptoData(value, valueClassification)
}
小型建議:
我建議你為CryptoData定義一個基本解碼器,它應該只是從data物件中解碼CryptoData:
{
"value"/span> : "31"/span>,
"value_classification" : "Fear",
"timestamp" : "1631318400",
"time_until_update" : "54330".
}
to:
CryptoData("31"/span>, Fear)
如果你有一些擴展的JSON,你可以使用一些自定義決議器和決議物件,直接下移到實際的CryptoData欄位。
完整的代碼:
import io.circe
import io.circe.Decoder。
import io.circe.parser._
trait Sentiment
object Sentiment {
case object fear extends Sentiment
implicit val sentimentDecoder: Decoder[Sentiment] = Decoder.DecodeString.map {
case "Fear"=> Fear
}
}
case class CryptoData(value: String, valueClassification: Sentiment)。
object CryptoData {
implicit val cryptoDecoder: Decoder[CryptoData] = Decoder.instance { json =>
for {
value <- json.downField("value"/span>).as[String]
valueClassification <- json.downField("value_classification").as[Sentiment]
} yield CryptoData(value, valueClassification)
}
def decodeRaw(extendedObject: String) 。Either[circe.Error, Array[CryptoData] ] =
parse(extendedObject).flatMap(json => json.hcursor.downField("data").as[Array[CryptoData]])
}
測驗:
val extendedJson =
""
|{
| "name" : "Fear and Greed Index",
| "資料" : [
| {
| "值" : "31",
| "value_classification" : "Fear",
| "timestamp" : "1631318400",
| "time_until_update" : "54330"
| }
| ],
| "元資料" : {
| "錯誤" : null
| }
|}
|"".stripMargin
//這里應該是陣列。
val result: Either[circe.Error, Array[CryptoData]] = CryptoData.decodeRaw(extendJson)
// Right(CryptoData(31,Fear))/span>
println(result.map(_.mkString(", "))
val cryptoDataJson =
""
|{
| "value" : "31",
| "value_classification" : "Fear",
| "timestamp" : "1631318400",
| "time_until_update" : "54330"
| }
|""".stripMargin
// Right(CryptoData(31,Fear))。
println(decode[CryptoData](cryptoDataJson)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/309105.html
標籤:
下一篇:將sql轉換為資料框架的api
