【问题标题】:decode json to List[A] in scala with Argonaut使用 Argonaut 在 scala 中将 json 解码为 List[A]
【发布时间】:2015-02-08 17:43:47
【问题描述】:

我有一个 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 时进入 for 理解。当我要求 List[Wf]

时,它甚至似乎都没有进入理解

如果我这样做了

json.decodeValidation[List[Wf]]

我明白了

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

我做错了什么?

【问题讨论】:

  • 最好看看失败的细节(使用decodeOption时隐藏)
  • 谢谢,最后列出了

标签: scala argonaut


【解决方案1】:

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

【讨论】:

  • 鉴于我需要从数组创建的每个对象中的数组外部的 soc 参数,您对如何解析它有什么建议吗?
  • 检查您的解码器,使其接受根对象作为 JSON。
  • 谢谢,我理解你对 { vs [ 事情的看法,这是有道理的,但我在文档中找不到任何地方谈论这个。抱歉我太密集了,我只是知道不够深入,无法弄清楚
【解决方案2】:

与其使用光标手动编写 DecodeJson 实例,不如使用 casecodec2 和 friends.GeneratedDecodeJsons 等方法更好

【讨论】:

  • 谢谢他们看起来确实更容易写,但它仍然不能解决我上面的问题。我已将 Wf 更改为 caseCodec4,将 WfId 更改为 caseCodec1,但在上述 json 上使用 decodeOption(List[Wf]) 时,我仍然得到 nil
  • 实际上,当我使用新方法执行 decodeOption[Wf] 时,我得到 None 而不是我使用游标得到的那个
猜你喜欢
  • 1970-01-01
  • 2015-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
相关资源
最近更新 更多