簡體   English   中英

使用Argonaut在scala中將json解碼為List [A]

[英]decode json to List[A] in scala with Argonaut

我有一個Wf類型

case class Wf(id: Option[WfId], socId: SocId, year: Int, employment: Float) extends WithId[WfId]

我有以下隱式函數定義了argonaut解碼器

implicit def WfDecodeJson: DecodeJson[Wf] = {
  DB.withSession {
    implicit session: Session =>
      DecodeJson(c => for {
        id <- (c --\ "id").as[Option[WfId]]
        socCode <- (c --\ "soc").as[Int]
        year <- c.--\("predictedEmployment").\\.--\("year").as[Int]
        employment <- c.--\("predictedEmployment").\\.--\("employment").as[Float]
      } yield Wf(None,
          SocSchema.socsTable.filter(_.code === 2216).first.id.get,
          year,
          employment))
  }
}

這是我要解碼的json

{
soc: 2216,
predictedEmployment: [
{
year: 2014,
employment: 19916.416015625
},
{
year: 2015,
employment: 20252.84375
},
{
year: 2016,
employment: 20345.037109375
},
{
year: 2017,
employment: 20640.29296875
},
{
year: 2018,
employment: 21200.6328125
},
{
year: 2019,
employment: 21564.833984375
},
{
year: 2020,
employment: 21896.298828125
},
{
year: 2021,
employment: 22376.546875
},
{
year: 2022,
employment: 22867.8828125
}
]
}

如果我做

json.decodeOption[Wf]

我得到預期的一些(Wf)

如果我做

json.decodeOption[List[Wf]]

我得到零。 如果我在隱式解碼器上添加斷點,當我只要求Wf時,它就會進入理解。 當我索要清單[Wf]時,似乎甚至沒有輸入要理解的內容。

如果我做

json.decodeValidation[List[Wf]]

我懂了

Failure([A]List[A]: [])

我究竟做錯了什么?

您的JSON以{開頭,而不是[ ,所以它不是一個可以解析為List[T]的數組。

與其使用游標手動編寫DecodeJson實例,不如使用casecodec2和friends之類的方法更好。

暫無
暫無

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

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