我目前正在编写一个从 openweathermaps api 中提取天气信息的程序。它返回一个 JSON 字符串,如下所示:
{"coord":{"lon":-95.94,"lat":41.26},"weather":[{"id":500,"main":"Rain","description":"light
rain","icon":"10n"}],"base":"stations","main": ...more json
我在下面有这个方法,它将字符串写入 .json 并允许我从中获取值。
public String readJSON() {
JSONParser parse = new JSONParser();
String ret = "";
try {
FileReader reader = new FileReader("C:\\Users\\mattm\\Desktop\\Java Libs\\JSON.json");
Object obj = parse.parse(reader);
JSONObject Jobj = (JSONObject) obj;
System.out.println(Jobj.get("weather"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(ret);
return ret;
}
问题是它只允许我获得诸如"coord"
and 之类的外部值"weather"
。所以目前因为我有System.out.println(Jobj.get("weather"));
它会返回[{"icon":"10n","description":"light rain","main":"Rain","id":500}]
但我想实际获得里面的description
值,比如值和main
值。我对 JSON 的工作不多,所以我可能遗漏了一些明显的东西。关于我如何做到这一点的任何想法?
您可以使用 JsonPath ( https://github.com/json-path/JsonPath ) 直接提取一些 json 字段/值。
var json = "{\"coord\":{\"lon\":\"-95.94\",\"lat\":\"41.26\"},\n" +
" \"weather\":[{\"id\":\"500\",\"main\":\"Rain\",\"description\":\"light\"}]}";
var main = JsonPath.read(json, "$.weather[0].main"); // Rain
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句