简体   繁体   English

播放框架 json 在数组中查找

[英]play framework json lookup inside array

I have simple json:我有简单的 json:

{
  "name": "John",
  "placesVisited": [
    {
      "name": "Paris",
      "data": {
        "weather": "warm",
        "date": "31/01/22"
      }
    },
    {
      "name": "New York",
      "data": [
        {
          "weather": "warm",
          "date": "31/01/21"
        },
        {
          "weather": "cold",
          "date": "28/01/21"
        }
      ]
    }
  ]
}

as you can see in this json there is placesVisited field, and if name is "New York" the "data" field is a List, and if the name is "Paris" its an object.正如您在这个 json 中看到的那样,有 placesVisited 字段,如果名称是“纽约”,则“数据”字段是一个列表,如果名称是“巴黎”,则它是一个 object。

what I want to do is to pull the placesVisited object where "name": "New York" and then I will parse it to a case class I have, I can't use this case class for both objects in placesVisited cause they have diff types for the same name.我想要做的是拉出 placesVisited object where "name": "New York" 然后我将它解析为一个案例 class 我有,我不能将这个案例 class 用于 placesVisited 中的两个对象因为它们有差异类型相同的名称。

so what I thought is to do something like:所以我想做的是:

(myJson \ "placesVisited") and here I need to add something that will give me element where name is "New York", how can I do that? (myJson \ "placesVisited")并且在这里我需要添加一些东西来给我名称为“New York”的元素,我该怎么做?

my result should be this:我的结果应该是这样的:

{
  "name": "New York",
  "data": [
    {
      "weather": "warm",
      "date": "31/01/21"
    },
    {
      "weather": "cold",
      "date": "28/01/21"
    }
  ]
}

something like this maybe can happen but its horrible haha:像这样的事情可能会发生,但它太可怕了哈哈:

(Json.parse(myjson) \ "placesVisited").as[List[JsObject]].find(item => {
  item.value.get("name").toString.contains("New York")
}).getOrElse(throw Exception("could not find New York element")).as[NewYorkModel]

item.value.get("name").toString can slightly be simplified to (item \ "name").as[String] but otherwise there's not much to improve. item.value.get("name").toString可以略微简化为(item \ "name").as[String]但除此之外没有太多可以改进的地方。

Another option is to use a case class Place(name: String, data: JsValue) and do it like this:另一种选择是使用case class Place(name: String, data: JsValue)并像这样:

(Json.parse(myjson) \ "placesVisited")
  .as[List[Place]]
  .find(_.name == "New York")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM