简体   繁体   中英

Parsing the openweatherMap json file

I am working on a project,which requires to get weather information and so i used openweathermap api. My program worked and i got information from "main" and "wind",but i also need to get description from the main weather set.The problem is that the weather set is a list in the json file and i am unable to cast it to map.The example json file which i am trying to parse is http://api.openweathermap.org/data/2.5/weather?q=London

JSON:

{
   "coord":{
      "lon":-0.13,
      "lat":51.51
   },
   "weather":[
      {
         "id":803,
         "main":"Clouds",
         "description":"broken clouds",
         "icon":"04n"
      }
   ],
   "base":"stations",
   "main":{
      "temp":43.56,
      "pressure":1004,
      "humidity":87,
      "temp_min":41,
      "temp_max":46.4
   },
   "visibility":10000,
   "wind":{
      "speed":11.41,
      "deg":80
   },
   "rain":{

   },
   "clouds":{
      "all":75
   },
   "dt":1573350303,
   "sys":{
      "type":1,
      "id":1414,
      "country":"GB",
      "sunrise":1573369754,
      "sunset":1573402780
   },
   "timezone":0,
   "id":2643743,
   "name":"London",
   "cod":200
}

When we look at the file,we notice that there is an [] bracket inside the weather set which is creating problems in my project.I tried to look up on how to cast list to map and tried playing with my code,but didn't help.The commented code in the file are things which i have tried while trying to make it work.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

import com.google.gson.*;
import com.google.gson.reflect.*;
import java.util.List;
import java.lang.reflect.Type; 

import java.util.HashMap;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class PlantWateringApp {

    public static Map<String, Object> jsonToMap(String str) {

        Map<String, Object> map = new Gson().fromJson(str, new TypeToken<HashMap<String, Object>>() {
        }.getType());
        return map;
    }

    public static void main(String[] args) {

        String LOCATION = "delhi,india";
        String result = "{\"coord\":{\"lon\":77.22,\"lat\":28.65},\"weather\":[{\"id\":711,\"main\":\"Smoke\",\"description\":\"smoke\",\"icon\":\"50d\"}],\"base\":\"stations\",\"main\":{\"temp\":72.32,\"pressure\":1015,\"humidity\":59,\"temp_min\":64.4,\"temp_max\":77},\"visibility\":1000,\"wind\":{\"speed\":3.36,\"deg\":270},\"clouds\":{\"all\":0},\"dt\":1573351180,\"sys\":{\"type\":1,\"id\":9165,\"country\":\"IN\",\"sunrise\":1573348168,\"sunset\":1573387234},\"timezone\":19800,\"id\":1273294,\"name\":\"Delhi\",\"cod\":200}";
        System.out.println(result);

        Map<String, Object> respMap = jsonToMap(result.toString());
        Map<String, Object> mainMap = jsonToMap(respMap.get("main").toString());
        Map<String, Object> windMap = jsonToMap(respMap.get("wind").toString());

        // Type listType = new TypeToken<List<Map<String,String>>>()
        // {}.getType();
        // List<Map<String,String>> weatherMap = new
        // Gson().fromJson(respMap.get("description").toString(),listType);

        // Map<String, Object> name = (Map<String, Object>)
        // respMap.get("description");

        // Map<String, Object > weatherMap = jsonToMap
        // (respMap.get("description").toString());

        System.out.println("Location: " + LOCATION);
        System.out.println("Current Temperature: " + mainMap.get("temp"));
        System.out.println("Current Humidity: " + mainMap.get("humidity"));
        System.out.println("Max: " + mainMap.get("temp_min"));
        System.out.println("Min: " + mainMap.get("temp_max"));

        System.out.println("Wind Speed: " + windMap.get("speed"));
        System.out.println("Wind Angle: " + windMap.get("deg"));

    }
}

I tried to do the same way as i did for main and wind: Map weatherMap = jsonToMap (respMap.get("weather").toString()); .But i got errors:

////java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 3 path $[0]

So i tried to not convert json to Map rather directly use map like Map weatherMap = (Map) respMap.get("weather"); but i got

////java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.util.Map

For this,i tried to cast list to map using

              List<Map<String,String>> weatherMap = new Gson().fromJson(respMap.get("weather").toString(),listType);

But this says:

//String cannot be converted to int

I am really confused on what to do in this situation.I am unable to figure out how to deal with [] in the json file.

As this data is provided as a List and you are trying to convert it into the Map . That is not right. You need to get it ( weather ) as a list of Map and then need to treat each element as Map . Here is an example how to get it as a Map

          ///...
          //// other code
          ///...      
          Map<String, Object > respMap = jsonToMap (result.toString());
          // don't need to convert from string to map again and again
          Map<String, Object > mainMap = (Map<String, Object >)respMap.get("main");
          Map<String, Object > windMap = (Map<String, Object >)respMap.get("wind");

          // fist get weather as list
          List<Map<String, Object >> weather = (List<Map<String, Object>>) (respMap.get("weather"));
            //...

          System.out.println("Wind Speed: " + windMap.get("speed")  );
          System.out.println("Wind Angle: " + windMap.get("deg")  );


          // weather as list
          System.out.println("Weather: "+ weather);

          // assuming weather contains at-least 1 element.
          Map<String, Object> weatherMap = weather.get(0);

          System.out.println("Weather as map: "+ weatherMap);

Casting it to list.

          List<Map<String, Object >> weather = (List<Map<String, Object>>) (respMap.get("weather"));

Then treat each element as Map:

// assuming weather contains at-least 1 element.
          Map<String, Object> weatherMap = weather.get(0);

Hope this helps.

Make life simple and use real types.

import java.util.List;

import com.google.gson.Gson;

public class PlantWateringApp {

    class Weather_2_5 {
        List<Weather> weather;
    }

    class Weather {
        Integer id;
        String main;
        String description;
        String icon;
    }

    public static void main(String[] args) {

        String result = "{\"coord\":{\"lon\":77.22,\"lat\":28.65},\"weather\":[{\"id\":711,\"main\":\"Smoke\",\"description\":\"smoke\",\"icon\":\"50d\"}],\"base\":\"stations\",\"main\":{\"temp\":72.32,\"pressure\":1015,\"humidity\":59,\"temp_min\":64.4,\"temp_max\":77},\"visibility\":1000,\"wind\":{\"speed\":3.36,\"deg\":270},\"clouds\":{\"all\":0},\"dt\":1573351180,\"sys\":{\"type\":1,\"id\":9165,\"country\":\"IN\",\"sunrise\":1573348168,\"sunset\":1573387234},\"timezone\":19800,\"id\":1273294,\"name\":\"Delhi\",\"cod\":200}";
        //System.out.println(result);

        Gson G = new Gson();
        Weather_2_5 obj = G.fromJson(result, Weather_2_5.class);

        for (int idx = 0; idx < obj.weather.size(); idx++) {
            System.out.println(obj.weather.get(idx).description);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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