【发布时间】:2019-09-21 05:12:47
【问题描述】:
我想使用 Circa 解析 JSON 字符串。您可以在下面找到输入 JSON 的示例。
这是一种递归数据。所以我的属性entity 包含实体的依赖关系。
我想解析依赖来映射Map[String, Tasks]。
{
"entity": [
{
"task_id": "X",
"type": "test",
"attributes": {
"name": "A",
"random_property_count": 1 // should be ignored
},
"dependencies": {
"random_name_1": {
"entity": [
{
"task_id": "907544AF",
"type": "test",
"attributes": {
"name": "B",
"random_attribute": "*"
},
"dependencies": {
"random_name_2": {
"entity": [
{
"task_id": "5",
"random_prop": "...", // should be ignored as it's not present in model
"type": "test",
"attributes": {
"name": "C"
}
}
]
}
}
}
]
}
}
}
]
}
这是我的代码:
case class Tasks (entity: Seq[Task])
case class Task(task_id: String, `type`: String, attributes: Attributes, dependencies: Map[String, Tasks])
case class Attributes(name: String)
implicit val decodeTask: Decoder[Task] = deriveDecoder[Task]
implicit val decodeTasks: Decoder[Tasks] = deriveDecoder[Tasks]
implicit val decodeAttributes: Decoder[Attributes] = deriveDecoder[Attributes]
val json = fromInputStream(getClass.getResourceAsStream("/json/example.json")).getLines.mkString
val tasks = decode[Tasks](json)
tasks match {
case Left(failure) => println(failure)
case Right(json) => println(json)
}
当我尝试将 JSON 字符串解析为我的模型时,我收到如下错误:
DecodingFailure(Attempt to decode value on failed cursor, List(DownField(dependencies), DownArray, DownField(entity), DownField(random_name_2), DownField(dependencies), DownArray, DownField(entity), DownField(random_name_1), DownField(dependencies), DownArray, DownField(entity)))
可能是什么问题?
【问题讨论】:
标签: json scala recursive-datastructures circe