[英]decode json to List[A] in scala with Argonaut
I have a type Wf which is 我有一个Wf类型
case class Wf(id: Option[WfId], socId: SocId, year: Int, employment: Float) extends WithId[WfId]
I have the following implicit function defining an argonaut decoder 我有以下隐式函数定义了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))
}
}
here is the json I am trying to decode 这是我要解码的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
}
]
}
if I do 如果我做
json.decodeOption[Wf]
I get the expected some(Wf) 我得到预期的一些(Wf)
if I do 如果我做
json.decodeOption[List[Wf]]
I get Nil. 我得到零。 If I add breakpoints to the implicit decoder it enters the for comprehension when i just ask for Wf. 如果我在隐式解码器上添加断点,当我只要求Wf时,它就会进入理解。 It dosn't even seem to enter the for comprehension when I ask for the List[Wf] 当我索要清单[Wf]时,似乎甚至没有输入要理解的内容。
if I do 如果我做
json.decodeValidation[List[Wf]]
I get 我懂了
Failure([A]List[A]: [])
What am I doing wrong? 我究竟做错了什么?
您的JSON以{
开头,而不是[
,所以它不是一个可以解析为List[T]
的数组。
与其使用游标手动编写DecodeJson实例,不如使用casecodec2和friends之类的方法更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.