Scala:如何用Circe解码对象列表



我的GreedIndex解码器不工作,但我似乎无法找出原因;我认为这是一件非常愚蠢的事情。

我想可能是timeStampList[CryptoData]的问题

case class CryptoData(greedValue: String, valueClassification: Sentiment, timeStamp: Long)
case class GreedIndex(name: String, data: List[CryptoData])
object GreedIndex {
implicit val greedDecoder: Decoder[GreedIndex] = Decoder.instance { json =>
for {
name <- json.get[String]("name")
data <- json.get[List[CryptoData]]("data")
} yield GreedIndex(name, data)
}
}
object CryptoData {
implicit val cryptoDecoder: Decoder[CryptoData] = Decoder.instance { json =>
val data = json.downField("data").downArray
for {
value               <- data.get[String]("value")
valueClassification <- data.get[Sentiment]("value_classification")
timestamp           <- data.get[String]("timestamp")
} yield CryptoData(value, valueClassification, timestamp.toLong * 1000)
}
}

JSON对象,我正在尝试解码。

{
"name" : "Fear and Greed Index",
"data" : [
{
"value" : "53",
"value_classification" : "Neutral",
"timestamp" : "1631750400",
"time_until_update" : "17264"
},
{
"value" : "49",
"value_classification" : "Neutral",
"timestamp" : "1631664000"
},
{
"value" : "30",
"value_classification" : "Fear",
"timestamp" : "1631577600"
}
],
"metadata" : {
"error" : null
}
}

方法如下:

import io.circe._
import io.circe.generic.extras.semiauto.deriveEnumerationDecoder
import io.circe.generic.semiauto.deriveDecoder
case class CryptoData(
greedValue: String,
valueClassification: Sentiment,
timeStamp: Long
)
object CryptoData {
implicit val decoder = Decoder.forProduct3(
"value",
"value_classification",
"timestamp"
)(CryptoData.apply)
}
sealed trait Sentiment
object Sentiment {
object Neutral extends Sentiment
object Fear extends Sentiment
implicit val decoder: Decoder[Sentiment] = deriveEnumerationDecoder
}
case class GreedIndex(name: String, data: List[CryptoData])
object GreedIndex {
implicit val greedDecoder: Decoder[GreedIndex] = deriveDecoder
}

GreedIndex的字段名与JSON中的字段名匹配,因此在这种情况下您可以只使用deriveDecoder。对于CryptoData,情况并非如此,因此您需要使用forProduct3手动编写。

由于您没有定义Sentiment,因此我将其建模为枚举。如果要使用deriveDecoder,则必须在JSON:{"Neutral": {}}中这样建模。要使用简单的String格式,您需要使用circe-generic-extras模块中的deriveEnumerationDecoder

最新更新