0

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?

Matt
  • 190
  • 1
  • 13
  • You can use `JsonPath` or `Rest Assured` which uses `gson path`. Both are great tools to read JSON files. You can also create POJO classes which represent the JSON. Cool stuff – Fenio May 05 '20 at 05:47
  • Using GSON with a POJO as answered by @souvikbachhar will be a better option. – NKR May 05 '20 at 09:26

3 Answers3

1

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
CodeScale
  • 3,046
  • 1
  • 12
  • 20
1

you can use

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

or you can declare user defined class according to structure and convert code using GSON

Gson gson= new Gson();
MyWeatherClass weather= gson.fromJSON(Jobj .toString(),MyWeatherClass.class);
System.out.println(weather.getCoord());
  • It seems I keep getting `The method getJSONArray(String) is undefined for the type JSONObject` when trying to call `getJSONArray()`. I have the gson and simple-jason dependancies. Is there any other I need? – Matt May 05 '20 at 16:07
  • Use below dependency to read JSON and remove simple JSON and you will not get undefined error. ` org.json json 20190722 ` – souvikbachhar May 06 '20 at 09:31
0

From the json sample that you have provided it can be seen that the "weather" actually is an array of objects, so you will have to treat it as such in code to get individual objects from the array when converted to Jsonobject. Try something like :

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;

}
Ananthapadmanabhan
  • 5,706
  • 6
  • 22
  • 39