繁体   English   中英

Android (Java) 在 json 中搜索字符串

[英]Android (Java) search for a string in json

我想寻找一个特定的国家,一旦我找到了这个国家,我想将相关数据打印到它。 到目前为止,我已经这样做了:

  boolean isFound = words.toString().indexOf("country one") != -1 ? true : false; //true
   if (isFound)
     {
       Toast.makeText(MainActivity.this, "FOUND", Toast.LENGTH_SHORT).show();
//     System.out.println()

     } else {
         Toast.makeText(MainActivity.this, "NOT FOUND", Toast.LENGTH_SHORT).show();
//       System.out.println()
     }

这是源 JSON:

[
  {
    "country": "country one",
    "city": "city one",
    "Start Time": "21th December 2019 09:00 AM",
    "End time": "22th December 2019 03:00 PM"
  },
  {
   "country": "country two",
    "city": "city two",
    "Start Time": "23th December 2019 09:00 AM",
    "End time": "23th December 2019 03:00 PM"
  },
  {
 "country": "country three",
    "city": "city three",
    "Start Time": "24th December 2019 09:00 AM",
    "End time": "24th December 2019 03:00 PM"
  } 
]

它似乎不起作用。

我真正想要的是当我输入一个国家时,只有那部分 JSON 会打印给我。

根据我的判断,您需要与“一国”相关的信息……或其他基于国家的信息。 您可以使用以下代码完成它:

public class ParseJSON {
  public static void main(String[] args) throws Exception {
    String searchString = "two";
    JSONArray arr = new JSONArray(words);
    for(int k = 0; k < arr.length(); k++) {
        JSONObject obj = arr.getJSONObject(k);
        if(obj.getString("country").contains(searchString)) {
            System.out.println("Country: " + obj.getString("country"));
            System.out.println("City: " + obj.getString("city"));
            System.out.println("Start Time: " + obj.getString("Start Time"));
            System.out.println("End Time: " + obj.getString("End time"));
          }
      }
  }
}

输出如下:

Country: country one City: city one Start Time: 21th December 2019 09:00 AM End Time: 22th December 2019 03:00 PM

我从这个链接使用了 json-20090211.jar .. https://mvnrepository.com/artifact/org.json/json/20090211

编辑 1:我假设 json 在一个文件中......如果作为字符串可用,则将“words”直接传递给 JSONArray 构造函数,它将起作用。

Edit2:由于 OP 已澄清 json 位于字符串变量中,因此不再需要 FileUtils。

暂无
暂无

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

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