首页 > 解决方案 > 如何正确使用 GSON 与 5 天预报 openweathermap 应用程序

问题描述

我正在尝试制作一个天气应用程序。我正在使用来自 openweathermap api 的 5 天预报,我想知道我是否正在正确解析和连接 api,因为它比当前天气 api 有更多的数据。谁能告诉我我的代码是否正确?这是我的代码的一部分。

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_weather_app, container, false);

    mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    mRecyclerView.addItemDecoration(new DividerItemDecoration(mRecyclerView.getContext(), DividerItemDecoration.VERTICAL));

    new GetWeatherAync().execute(getActivity());
    return view;


}
  private class GetWeatherAync extends AsyncTask<Context, Void,      
List<ForecastWeatherList>> {
    private String TAG = GetWeatherAync.class.getSimpleName();
    private Context mContext;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected List<ForecastWeatherList> doInBackground(Context...params) {
        mContext = params[0];
        return getWeatherFromServer();
    }

    @Override
    protected void onPostExecute(List<ForecastWeatherList> result) {
        super.onPostExecute(result);

        if (result != null) {
            Log.e(TAG, "populate UI recycler view with gson converted data");

            RecyclerViewAdapter weatherRecyclerViewAdapter = new RecyclerViewAdapter(result, mContext);
            mRecyclerView.setAdapter(weatherRecyclerViewAdapter);
        }

    }
}

public List<ForecastWeatherList> getWeatherFromServer(){
    String serviceUrl = "http://api.openweathermap.org/data/2.5/forecast?q=" + searchView + api_key;
    URL url = null;
    try {
        url = new URL(serviceUrl);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.setConnectTimeout(4000);
        connection.setReadTimeout(4000);
        connection.connect();

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

        //pass buffered reader to convert json to javaobject using gson
        return convertJsonToObject(bufferedReader);

    }catch (Exception e){

    }

    return null;
}

public List<ForecastWeatherList> convertJsonToObject(BufferedReader bufferedReader){
    final Gson gson = new Gson();

    //pass root element type to fromJson method along with input stream

    ForecastWeatherListWrapper weatherWrapper = gson.fromJson(bufferedReader,ForecastWeatherListWrapper.class);

    List<ForecastWeatherList> weatherlst = weatherWrapper.getforecastWeatherLists();

    return weatherlst;
}

这是我的 GSON 代码。有 Clouds、Main、Rain、Sys、Weather 和 Wind 的类。

public class ForecastWeatherList {
@SerializedName("dt")
@Expose
private Integer dt;
@SerializedName("main")
@Expose
private Main main;
@SerializedName("weather")
@Expose
private Weather weather = null;
@SerializedName("clouds")
@Expose
private Clouds clouds;
@SerializedName("wind")
@Expose
private Wind wind;
@SerializedName("rain")
@Expose
private Rain rain;
@SerializedName("sys")
@Expose
private Sys sys;
@SerializedName("dt_txt")
@Expose
private String dtTxt;

public Integer getDt() {
    return dt;
}

public void setDt(Integer dt) {
    this.dt = dt;
}

public Main getMain() {
    return main;
}

public void setMain(Main main) {
    this.main = main;
}

public Weather getWeather() {
    return (Weather) weather;
}

public void setWeather(Weather weather) {
    this.weather = weather;
}

public Clouds getClouds() {
    return clouds;
}

public void setClouds(Clouds clouds) {
    this.clouds = clouds;
}

public Wind getWind() {
    return wind;
}

public void setWind(Wind wind) {
    this.wind = wind;
}

public Rain getRain() {
    return rain;
}

public void setRain(Rain rain) {
    this.rain = rain;
}

public Sys getSys() {
    return sys;
}

public void setSys(Sys sys) {
    this.sys = sys;
}

public String getDtTxt() {
    return dtTxt;
}

public void setDtTxt(String dtTxt) {
    this.dtTxt = dtTxt;
}

}

这是我正在使用的包装器。

  public class ForecastWeatherListWrapper {

  private List<ForecastWeatherList> forecastWeatherLists;

public List<ForecastWeatherList> getforecastWeatherLists() {
    return forecastWeatherLists;
}

public void setforecastWeatherLists(List<ForecastWeatherList> forecastWeatherItems){

    this.forecastWeatherLists = forecastWeatherItems;
}

}

这是我第一次使用 GSON 解析 JSON 数据,所以我的问题是我是否正确使用它来解析我的 JSON 数据,因为还有其他类,例如 Main、Clouds 等,以及我是否连接到正确使用 api 上网。谢谢。

这是我的主要课程:

public class Main {

@SerializedName("temp")
@Expose
private Double temp;
@SerializedName("temp_min")
@Expose
private Double tempMin;
@SerializedName("temp_max")
@Expose
private Double tempMax;
@SerializedName("pressure")
@Expose
private Double pressure;
@SerializedName("sea_level")
@Expose
private Double seaLevel;
@SerializedName("grnd_level")
@Expose
private Double grndLevel;
@SerializedName("humidity")
@Expose
private Integer humidity;
@SerializedName("temp_kf")
@Expose
private Integer tempKf;

public Double getTemp() {
    return temp;
}

    public void setTemp(Double temp) {
        this.temp = temp;
    }

    public Double getTempMin() {
        return tempMin;
    }

    public void setTempMin(Double tempMin) {
        this.tempMin = tempMin;
    }

    public Double getTempMax() {
        return tempMax;
    }

    public void setTempMax(Double tempMax) {
        this.tempMax = tempMax;
    }

public Double getPressure() {
    return pressure;
}

public void setPressure(Double pressure) {
    this.pressure = pressure;
}

public Double getSeaLevel() {
    return seaLevel;
}

public void setSeaLevel(Double seaLevel) {
    this.seaLevel = seaLevel;
}

public Double getGrndLevel() {
    return grndLevel;
}

public void setGrndLevel(Double grndLevel) {
    this.grndLevel = grndLevel;
}

public Integer getHumidity() {
    return humidity;
}

public void setHumidity(Integer humidity) {
    this.humidity = humidity;
}

public Integer getTempKf() {
    return tempKf;
}

public void setTempKf(Integer tempKf) {
    this.tempKf = tempKf;
}

}

这是我的原始字符串数据(我认为)。

 "cod":"200",
"message":0.0074,
  "cnt":39,
"list":[
  {
     "dt":1534215600,
     "main":{
        "temp":293.24,
        "temp_min":292.346,
        "temp_max":293.24,
        "pressure":1021.77,
        "sea_level":1028.21,
        "grnd_level":1021.77,
        "humidity":100,
        "temp_kf":0.89
     },
     "weather":[
        {
           "id":500,
           "main":"Rain",
           "description":"light rain",
           "icon":"10n"
        }
     ],
     "clouds":{
        "all":20
     },
     "wind":{
        "speed":2.51,
        "deg":275.001
     },
     "rain":{
        "3h":0.0050000000000008
     },
     "sys":{
        "pod":"n"
     },
     "dt_txt":"2018-08-14 03:00:00"
  },
  {
     "dt":1534226400,
     "main":{
        "temp":292.3,
        "temp_min":291.706,
        "temp_max":292.3,
        "pressure":1020.99,
        "sea_level":1027.42,
        "grnd_level":1020.99,
        "humidity":100,
        "temp_kf":0.6
     },
     "weather":[
        {
           "id":800,
           "main":"Clear",
           "description":"clear sky",
           "icon":"01n"
        }
     ],
     "clouds":{
        "all":0
     },
     "wind":{
        "speed":2.52,
        "deg":294.505
     },
     "rain":{

     },
     "sys":{
        "pod":"n"
     },
     "dt_txt":"2018-08-14 06:00:00"
  },
  {
     "dt":1534237200,
     "main":{
        "temp":291.07,
        "temp_min":290.77,
        "temp_max":291.07,
        "pressure":1020.65,
        "sea_level":1027.03,
        "grnd_level":1020.65,
        "humidity":100,
        "temp_kf":0.3
     },
     "weather":[
        {
           "id":800,
           "main":"Clear",
           "description":"clear sky",
           "icon":"01n"
        }
     ],
     "clouds":{
        "all":0
     },
     "wind":{
        "speed":1.31,
        "deg":225.5
     },
     "rain":{

     },
     "sys":{
        "pod":"n"
     },
     "dt_txt":"2018-08-14 09:00:00"
  },
  {
     "dt":1534248000,
     "main":{
        "temp":293.286,
        "temp_min":293.286,
        "temp_max":293.286,
        "pressure":1020.78,
        "sea_level":1027.17,
        "grnd_level":1020.78,
        "humidity":100,
        "temp_kf":0
     },
     "weather":[
        {
           "id":800,
           "main":"Clear",
           "description":"clear sky",
           "icon":"02d"
        }
     ],
     "clouds":{
        "all":8
     },
     "wind":{
        "speed":2.83,
        "deg":234.501
     },
     "rain":{

     },
     "sys":{
        "pod":"d"
     },
     "dt_txt":"2018-08-14 12:00:00"
  },
  {
     "dt":1534258800,
     "main":{
        "temp":298.671,
        "temp_min":298.671,
        "temp_max":298.671,
        "pressure":1020.76,
        "sea_level":1027.15,
        "grnd_level":1020.76,
        "humidity":92,
        "temp_kf":0
     },
     "weather":[
        {
           "id":800,
           "main":"Clear",
           "description":"clear sky",
           "icon":"01d"
        }
     ],
     "clouds":{
        "all":0
     },
     "wind":{
        "speed":2.71,
        "deg":259.5
     },
     "rain":{

     },
     "sys":{
        "pod":"d"
     },
     "dt_txt":"2018-08-14 15:00:00"
  },
  {
     "dt":1534269600,
     "main":{
        "temp":300.7,
        "temp_min":300.7,
        "temp_max":300.7,
        "pressure":1019.76,
        "sea_level":1026.18,
        "grnd_level":1019.76,
        "humidity":83,
        "temp_kf":0
     },
     "weather":[
        {
           "id":500,
           "main":"Rain",
           "description":"light rain",
           "icon":"10d"
        }
     ],
     "clouds":{
        "all":24
     },
     "wind":{
        "speed":3.66,
        "deg":285.503
     },
     "rain":{
        "3h":1.11
     },
     "sys":{
        "pod":"d"
     },
     "dt_txt":"2018-08-14 18:00:00"
  },
  {
     "dt":1534280400,
     "main":{
        "temp":298.464,
        "temp_min":298.464,
        "temp_max":298.464,
        "pressure":1019.68,
        "sea_level":1025.97,
        "grnd_level":1019.68,
        "humidity":83,
        "temp_kf":0
     },
     "weather":[
        {
           "id":500,
           "main":"Rain",
           "description":"light rain",
           "icon":"10d"
        }
     ],
     "clouds":{
        "all":48
     },
     "wind":{
        "speed":3.27,
        "deg":289.504
     },
     "rain":{
        "3h":1.61
     },
     "sys":{
        "pod":"d"
     },
     "dt_txt":"2018-08-14 21:00:00"
  },
  {
     "dt":1534291200,
     "main":{
        "temp":297.882,
        "temp_min":297.882,
        "temp_max":297.882,
        "pressure":1020,
        "sea_level":1026.37,
        "grnd_level":1020,
        "humidity":82,
        "temp_kf":0
     },
     "weather":[
        {
           "id":500,
           "main":"Rain",
           "description":"light rain",
           "icon":"10n"
        }
     ],
     "clouds":{
        "all":36
     },
     "wind":{
        "speed":2.37,
        "deg":275.004
     },
     "rain":{
        "3h":0.13
     },
     "sys":{
        "pod":"n"
     },
     "dt_txt":"2018-08-15 00:00:00"
  },
  {
     "dt":1534302000,
     "main":{
        "temp":295.242,
        "temp_min":295.242,
        "temp_max":295.242,
        "pressure":1021.11,
        "sea_level":1027.53,
        "grnd_level":1021.11,
        "humidity":94,
        "temp_kf":0
     },
     "weather":[
        {
           "id":802,
           "main":"Clouds",
           "description":"scattered clouds",
           "icon":"03n"
        }
     ],
     "clouds":{
        "all":32
     },
     "wind":{
        "speed":1.26,
        "deg":313.002
     },
     "rain":{

     },
     "sys":{
        "pod":"n"
     },
     "dt_txt":"2018-08-15 03:00:00"
  },
  {
     "dt":1534312800,
     "main":{
        "temp":294.05,
        "temp_min":294.05,
        "temp_max":294.05,
        "pressure":1021.27,
        "sea_level":1027.77,
        "grnd_level":1021.27,
        "humidity":100,
        "temp_kf":0
     },
     "weather":[
        {
           "id":800,
           "main":"Clear",
           "description":"clear sky",
           "icon":"01n"
        }
     ],
     "clouds":{
        "all":0
     },
     "wind":{
        "speed":2.46,
        "deg":274.504
     },
     "rain":{

     },
     "sys":{
        "pod":"n"
     },
     "dt_txt":"2018-08-15 06:00:00"
  },
  {
     "dt":1534323600,
     "main":{
        "temp":293.495,
        "temp_min":293.495,
        "temp_max":293.495,
        "pressure":1021.36,
        "sea_level":1027.7,
        "grnd_level":1021.36,
        "humidity":100,
        "temp_kf":0
     },
     "weather":[
        {
           "id":800,
           "main":"Clear",
           "description":"clear sky",
           "icon":"01n"
        }
     ],
     "clouds":{
        "all":0
     },
     "wind":{
        "speed":3.01,
        "deg":277.505
     },
     "rain":{

     },
     "sys":{
        "pod":"n"
     },
     "dt_txt":"2018-08-15 09:00:00"
],
"city":{
  "id":4347778,
  "name":"Baltimore",
  "coord":{
     "lat":39.2909,
     "lon":-76.6108
  },
  "country":"US",
  "population":620961

} }

标签: androidjsonapigsonopenweathermap

解决方案


您必须首先获取“列表”对象。

要么首先将列表解析为 Json 对象,要么执行“ForecastWeatherListWrapper”

public class ForecastWeatherListWrapper {

   @SerializedName("list")
   @Expose
   private List<ForecastWeatherList> forecastWeatherLists;

   public List<ForecastWeatherList> getforecastWeatherLists() {
        return forecastWeatherLists;
    }

    public void setforecastWeatherLists(List<ForecastWeatherList> forecastWeatherItems){

       this.forecastWeatherLists = forecastWeatherItems;
    }
}

推荐阅读