如何为列表中的每个JObject获取密钥scenario0
和scenario1
?
便便是:
poop: List[org.json4s.JsonAST.JValue] = List(JObject(List((street,JString(Bulevard)), (city,JString(Helsinki)))), JObject(List((street,JString(Bulevard)), (city,JString(Helsinki)))))
代码:
import org.json4s.jackson.JsonMethods._
import org.json4s._
implicit val formats = DefaultFormats
val json = parse("""
{
"address0": {
"scenario0": {
"street": "Bulevard",
"city": "Helsinki"
},
"scenario1": {
"street": "Bulevard",
"city": "Helsinki"
}
},
"address1": {
"scenario0": {
"street": "Bulevard",
"city": "Helsinki"
},
"scenario1": {
"street": "Bulevard",
"city": "Helsinki"
}
}
}""")
val poop = (json \ "address0").children
poop.foreach(p => {
})
答案 0 :(得分:1)
你的意思是你想要这样,就像JObject
每个人一样。
json.children.flatMap(_.children)
res13: List[JValue] = List(
JObject(List((street,JString(Bulevard)), (city,JString(Helsinki)))),
JObject(List((street,JString(Bulevard)), (city,JString(Helsinki)))),
JObject(List((street,JString(Bulevard)), (city,JString(Helsinki)))),
JObject(List((street,JString(Bulevard)), (city,JString(Helsinki))))
)
但您可能会发现使用像circe,play-json或argonaut这样的库将它们解析为案例类会更有用。这样你就不必在任何地方继续解析json。
答案 1 :(得分:1)
val poop: Map[String, Any] = json.asInstanceOf[JObject].values
返回Map(address0 -> Map(scenario0 -> Map(street -> Bulevard, city -> Helsinki), scenario1 -> Map(street -> Bulevard, city -> Helsinki)), address1 -> Map(scenario0 -> Map(street -> Bulevard, city -> Helsinki), scenario1 -> Map(street -> Bulevard, city -> Helsinki)))
val poop = json.asInstanceOf[JObject].obj
提供List[org.json4s.JsonAST.JField] = List((address0,JObject(List((scenario0,JObject(List((street,JString(Bulevard)), (city,JString(Helsinki))))), (scenario1,JObject(List((street,JString(Bulevard)), (city,JString(Helsinki)))))))), (address1,JObject(List((scenario0,JObject(List((street,JString(Bulevard)), (city,JString(Helsinki))))), (scenario1,JObject(List((street,JString(Bulevard)), (city,JString(Helsinki)))))))))
P.S。为简单起见,我省略了监护人检查。