从 .json 获取 JSON 值

Getting JSON values from a .json

我目前正在编写一个从 openweathermaps api 中提取天气信息的程序。它 return 是一个 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""weather"。所以目前因为我有 System.out.println(Jobj.get("weather")); 它会 return [{"icon":"10n","description":"light rain","main":"Rain","id":500}] 但我想实际得到里面的值,比如 description 值和 main价值。我对 JSONs 的工作不多,所以我可能缺少一些明显的东西。关于如何执行此操作的任何想法?

您可以使用 JsonPath (https://github.com/json-path/JsonPath) 直接提取一些 json field/values。

 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

你可以使用

JSONObject Jobj = (JSONObject) obj;
System.out.println(Jobj.getJSONObject("coord").get("lon");//here coord is json object
System.out.println(Jobj.getJSONArray("weather").get(0).get("description");//for array

或者您可以根据结构声明用户定义的class并使用GSON

转换代码
Gson gson= new Gson();
MyWeatherClass weather= gson.fromJSON(Jobj .toString(),MyWeatherClass.class);
System.out.println(weather.getCoord());

从您提供的 json 示例中可以看出 "weather" 实际上是一个对象数组,因此您必须在代码中这样对待它才能获取单个对象从数组转换为 Jsonobject 时。 尝试类似的东西:

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;
    JSONArray jobjWeatherArray = jobj.getJSONArray("weather")

    for (int i = 0; i < jobjWeatherArray.length(); i++) {
      JSONObject jobjWeather = jobjWeatherArray.getJSONObject(i);
      System.out.println(jobjWeather.get("id"));
      System.out.println(jobjWeather.get("main"));
      System.out.println(jobjWeather.get("description"));
    }

} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} catch (ParseException e) {
    e.printStackTrace();
}
System.out.println(ret);
return ret;

}