1
我得到给定的(例如)JSON:解析JSON列表Scala中两个列表,瑟茜
{
"version": 1.1,
"author": "XYZ",
"elements": [{
"type": "nodeX",
"id": 1,
"a": 1,
"b": 2
},
{
"type": "nodeX",
"id": 2,
"a": 1,
"b": 2
},
...
{
"type": "nodeX",
"id": 13214,
"a": 1,
"b": 2
},
{
"type": "nodeY",
"id": 1,
"c": [
"qaz",
"wsx"
]
},
{
"type": "nodeY",
"id": 2,
"c": [
"qaz",
"wsx"
]
},
...
{
"type": "nodeY",
"id": 3,
"c": [
"qaz",
"wsx"
]
}
]
}
元素列表总是包含有类型的对象 “节点X” 和属性:ID,一个和b或类型为“nodeY”的物体和属性:id和c。
我使用瑟茜(Scala库)这个JSON解析到类:
case class Element(val 'type':String, val id:Long, val a:Option[Long],val b:Option[Long], val c:Option[List[String]])
case class MyJson(val version:Double, val author:String, val elements:List[Element])
但urfortunately我买了可选字段对象的元素列表。我需要给定类的两个列表:
case class NodeX(val id:Long, val a:Long, val b:Long)
case class NodeY(val id:Long, val c:List[String])
所以现在我用这:
val elements = // MyJson.elements
for (elem <- elements)
elem match {
case Element("nodeX", _,_,_,_) => //here convert to NodeX and add to list List[NodeX]
case Element("nodeY", _,_,_,_) => //here convert to NodeY and add to list List[NodeY]
}
我要寻找更好的解决办法,更快的解决方案,因为列表在这个JSON包含从不小于70K元素。
感谢提前:)
你怎么解码?半自动派生解码器? – michaJlS
@michaJlS我用'decode [MyJson](json)'解码,我对circe没有经验。我读过半自动派生解码器,但我不知道如何使用 – BoyFarmer
你将不得不显示你的解析代码,并告诉你从这个JSON中取出的位置。 – michaJlS