使用Argonaut将json解码为scala中的List [A]

时间:2015-02-08 17:43:48

标签: scala 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]]

我得到了Nil。如果我向隐式解码器添加断点,当我要求Wf时,它会进入for comprehension。当我要求List [Wf]

时,它似乎甚至无法进入理解状态

如果我这样做

json.decodeValidation[List[Wf]]

我得到了

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

我做错了什么?

2 个答案:

答案 0 :(得分:1)

您的JSON以{开头,而不是[,因此它不是可以解析为List[T]的数组。

答案 1 :(得分:0)

不是手动使用游标手动编写DecodeJson实例,而是使用casecodec2和friends.GeneratedDecodeJsons等方法会更好。