Search code examples
javajsonapi-design

Getting JSON values from a .json


I am currently writing a program that pulls weather info from openweathermaps api. It returns a JSON string such as this:

{"coord":{"lon":-95.94,"lat":41.26},"weather":[{"id":500,"main":"Rain","description":"light 
rain","icon":"10n"}],"base":"stations","main": ...more json

I have this method below which writes the string to a .json and allows me to get the values from it.

    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;

}

The problem is it only allows me to get the outer values such as "coord" and "weather". So currently since I have System.out.println(Jobj.get("weather")); it will return [{"icon":"10n","description":"light rain","main":"Rain","id":500}] but I want to actually get the values that are inside of that like the description value and the main value. I haven't worked much with JSONs so there may be something obvious I am missing. Any ideas on how I would do this?


Solution

  • You can use JsonPath (https://github.com/json-path/JsonPath) to extract some json field/values directly.

     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