使用json4s-jackson解析密钥和值的JObject

时间:2017-05-20 06:07:38

标签: json scala json4s

如何为列表中的每个JObject获取密钥scenario0scenario1

便便是:

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 => {

})

2 个答案:

答案 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)

  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)))
  2. 如果您需要值并且具有固定架构,那么extracting of case class可能会有用。
  3. 如果您需要AST: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)))))))))
  4. P.S。为简单起见,我省略了监护人检查。