我如何使用gson从baidu weather api解析json

时间:2015-10-02 15:04:19

标签: android json gson

这是

的网址

baidu weather api

json是

{
  "error": 0,
  "status": "success",
  "date": "2015-10-02",
  "results": [
    {
      "currentCity": "beijing",
      "pm25": "81",
      "index": [
        {
          "title": "穿衣",
          "zs": "舒适",
          "tipt": "穿衣指数",
          "des": "建议着长袖T恤、衬衫加单裤等服装。年老体弱者宜着针织长袖衬衫、马甲和长裤。"
        },
        {
          "title": "洗车",
          "zs": "较适宜",
          "tipt": "洗车指数",
          "des": "较适宜洗车,未来一天无雨,风力较小,擦洗一新的汽车至少能保持一天。"
        },
        {
          "title": "旅游",
          "zs": "适宜",
          "tipt": "旅游指数",
          "des": "天气较好,温度适宜,是个好天气哦。这样的天气适宜旅游,您可以尽情地享受大自然的风光。"
        },
        {
          "title": "感冒",
          "zs": "少发",
          "tipt": "感冒指数",
          "des": "各项气象条件适宜,无明显降温过程,发生感冒机率较低。"
        },
        {
          "title": "运动",
          "zs": "较适宜",
          "tipt": "运动指数",
          "des": "天气较好,户外运动请注意防晒。推荐您进行室内运动。"
        },
        {
          "title": "紫外线强度",
          "zs": "强",
          "tipt": "紫外线强度指数",
          "des": "紫外线辐射强,建议涂擦SPF20左右、PA++的防晒护肤品。避免在10点至14点暴露于日光下。"
        }
      ],
      "weather_data": [
        {
          "date": "周五 10月02日 (实时:18℃)",
          "dayPictureUrl": "http://api.map.baidu.com/images/weather/day/qing.png",
          "nightPictureUrl": "http://api.map.baidu.com/images/weather/night/qing.png",
          "weather": "晴",
          "wind": "微风",
          "temperature": "26 ~ 12℃"
        },
        {
          "date": "周六",
          "dayPictureUrl": "http://api.map.baidu.com/images/weather/day/qing.png",
          "nightPictureUrl": "http://api.map.baidu.com/images/weather/night/qing.png",
          "weather": "晴",
          "wind": "微风",
          "temperature": "25 ~ 12℃"
        },
        {
          "date": "周日",
          "dayPictureUrl": "http://api.map.baidu.com/images/weather/day/duoyun.png",
          "nightPictureUrl": "http://api.map.baidu.com/images/weather/night/duoyun.png",
          "weather": "多云",
          "wind": "微风",
          "temperature": "25 ~ 13℃"
        },
        {
          "date": "周一",
          "dayPictureUrl": "http://api.map.baidu.com/images/weather/day/qing.png",
          "nightPictureUrl": "http://api.map.baidu.com/images/weather/night/qing.png",
          "weather": "晴",
          "wind": "微风",
          "temperature": "26 ~ 13℃"
        }
      ]
    }
  ]
}

我想用gson解析它,但我遇到了一些问题。

在我的WeatherInfo.java中 我写的就像

public class WeatherInfo
{
    private String error;
    private String status;
    private String date;
    public String getError() {return error;}
    public void  setError(String error) {this.error = error;}
    public String getStatus() {return status;}
    public void setStatus(String status) {this.status = status;}
    public String getDate(){return date;}
    public void setDate(String date){this.date = date;}
    public Results results;
    public Results getResults(){return results;}
    public void setResults(Results results){this.results = results;}

    public static class Results
    {
        public String currentCity;
        public String pm25;
        public String getCurrentCity(){return currentCity;}
        public void setCurrentCity(String currentCity){this.currentCity = currentCity;}
        public String getPm25(){return pm25;}
        public void setPm25(String pm25){this.pm25 = pm25;}

        public Index getIndex() {
            return index;
        }

        public void setIndex(Index index) {
            this.index = index;
        }

        public Index index;

        public Weather_data getWeather_data() {
            return weather_data;
        }

        public void setWeather_data(Weather_data weather_data) {
            this.weather_data = weather_data;
        }

        public Weather_data weather_data;
        public static class Index
        {
            private String title;
            private String zs;
            private String des;
            private String tipt;

            public String getTitle(){return title;}
            public void setTitle(String title){this.title = title;}
            public String getZs(){return zs;}
            public void setZs(String zs){this.zs = zs;}
            public String getTipt() {return tipt;}
            public void setTipt(String tipt) {this.tipt = tipt;}
            public String getDes() {return des;}
            public void setDes(String des) {this.des = des;}

        }
        public class Weather_data
        {
            private String data;
            private String dayPictureUrl;
            private String nightPictureUrl;
            private String weather;
            private String wind;
            private String temperature;

            public String getData() {
                return data;
            }

            public void setData(String data) {
                this.data = data;
            }

            public String getDayPictureUrl() {
                return dayPictureUrl;
            }

            public void setDayPictureUrl(String dayPictureUrl) {
                this.dayPictureUrl = dayPictureUrl;
            }

            public String getNightPictureUrl() {
                return nightPictureUrl;
            }

            public void setNightPictureUrl(String nightPictureUrl) {
                this.nightPictureUrl = nightPictureUrl;
            }

            public String getWeather() {
                return weather;
            }

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

            public String getWind() {
                return wind;
            }

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

            public String getTemperature() {
                return temperature;
            }

            public void setTemperature(String temperature) {
                this.temperature = temperature;
            }



        }

    }

}

我使用此函数来解析json

public void parseJsonWithGson(String jsonData) {
    Log.d(TAG,"用gson进行解析");
    Gson gson = new Gson();
    WeatherInfo weatherInfo = gson.fromJson(jsonData,WeatherInfo.class);
    Log.d(TAG,"weatherInfo"+weatherInfo);
    Log.d(TAG,"error is "+weatherInfo.getError());
    Log.d(TAG,"status is "+weatherInfo.getStatus());
    Log.d(TAG,"date is "+weatherInfo.getDate());
    Log.d(TAG,"currentcity is "+weatherInfo.getResults().getCurrentCity());
}

最后有一个错误

Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 62 path $.results

2 个答案:

答案 0 :(得分:0)

result对我来说就像一个数组,你的GSON模型应该是:

public List<Results> results;
public List<Results> getResults(){return results;}

然后解析时

Log.d(TAG,"currentcity is "+weatherInfo.getResults().get(0).getCurrentCity());

无论如何,你不应该手动编写这个模型,有些工具可以帮助你生成POJO类。例如:

http://www.jsonschema2pojo.org/

我为你制作了课程:

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import java.util.ArrayList;
import java.util.List;


public class WeatherInfo {
    @SerializedName("error")
    @Expose
    private Integer error;
    @SerializedName("status")
    @Expose
    private String status;
    @SerializedName("date")
    @Expose
    private String date;
    @SerializedName("results")
    @Expose
    private List<Result> results = new ArrayList<Result>();

    /**
     * @return The error
     */
    public Integer getError() {
        return error;
    }

    /**
     * @param error The error
     */
    public void setError(Integer error) {
        this.error = error;
    }

    /**
     * @return The status
     */
    public String getStatus() {
        return status;
    }

    /**
     * @param status The status
     */
    public void setStatus(String status) {
        this.status = status;
    }

    /**
     * @return The date
     */
    public String getDate() {
        return date;
    }

    /**
     * @param date The date
     */
    public void setDate(String date) {
        this.date = date;
    }

    /**
     * @return The results
     */
    public List<Result> getResults() {
        return results;
    }

    /**
     * @param results The results
     */
    public void setResults(List<Result> results) {
        this.results = results;
    }


    public class Index {

        @SerializedName("title")
        @Expose
        private String title;
        @SerializedName("zs")
        @Expose
        private String zs;
        @SerializedName("tipt")
        @Expose
        private String tipt;
        @SerializedName("des")
        @Expose
        private String des;

        /**
         * @return The title
         */
        public String getTitle() {
            return title;
        }

        /**
         * @param title The title
         */
        public void setTitle(String title) {
            this.title = title;
        }

        /**
         * @return The zs
         */
        public String getZs() {
            return zs;
        }

        /**
         * @param zs The zs
         */
        public void setZs(String zs) {
            this.zs = zs;
        }

        /**
         * @return The tipt
         */
        public String getTipt() {
            return tipt;
        }

        /**
         * @param tipt The tipt
         */
        public void setTipt(String tipt) {
            this.tipt = tipt;
        }

        /**
         * @return The des
         */
        public String getDes() {
            return des;
        }

        /**
         * @param des The des
         */
        public void setDes(String des) {
            this.des = des;
        }

    }


    public class Result {

        @SerializedName("currentCity")
        @Expose
        private String currentCity;
        @SerializedName("pm25")
        @Expose
        private String pm25;
        @SerializedName("index")
        @Expose
        private List<Index> index = new ArrayList<Index>();
        @SerializedName("weather_data")
        @Expose
        private List<WeatherDatum> weatherData = new ArrayList<WeatherDatum>();

        /**
         * @return The currentCity
         */
        public String getCurrentCity() {
            return currentCity;
        }

        /**
         * @param currentCity The currentCity
         */
        public void setCurrentCity(String currentCity) {
            this.currentCity = currentCity;
        }

        /**
         * @return The pm25
         */
        public String getPm25() {
            return pm25;
        }

        /**
         * @param pm25 The pm25
         */
        public void setPm25(String pm25) {
            this.pm25 = pm25;
        }

        /**
         * @return The index
         */
        public List<Index> getIndex() {
            return index;
        }

        /**
         * @param index The index
         */
        public void setIndex(List<Index> index) {
            this.index = index;
        }

        /**
         * @return The weatherData
         */
        public List<WeatherDatum> getWeatherData() {
            return weatherData;
        }

        /**
         * @param weatherData The weather_data
         */
        public void setWeatherData(List<WeatherDatum> weatherData) {
            this.weatherData = weatherData;
        }


        public class WeatherDatum {

            @SerializedName("date")
            @Expose
            private String date;
            @SerializedName("dayPictureUrl")
            @Expose
            private String dayPictureUrl;
            @SerializedName("nightPictureUrl")
            @Expose
            private String nightPictureUrl;
            @SerializedName("weather")
            @Expose
            private String weather;
            @SerializedName("wind")
            @Expose
            private String wind;
            @SerializedName("temperature")
            @Expose
            private String temperature;

            /**
             * @return The date
             */
            public String getDate() {
                return date;
            }

            /**
             * @param date The date
             */
            public void setDate(String date) {
                this.date = date;
            }

            /**
             * @return The dayPictureUrl
             */
            public String getDayPictureUrl() {
                return dayPictureUrl;
            }

            /**
             * @param dayPictureUrl The dayPictureUrl
             */
            public void setDayPictureUrl(String dayPictureUrl) {
                this.dayPictureUrl = dayPictureUrl;
            }

            /**
             * @return The nightPictureUrl
             */
            public String getNightPictureUrl() {
                return nightPictureUrl;
            }

            /**
             * @param nightPictureUrl The nightPictureUrl
             */
            public void setNightPictureUrl(String nightPictureUrl) {
                this.nightPictureUrl = nightPictureUrl;
            }

            /**
             * @return The weather
             */
            public String getWeather() {
                return weather;
            }

            /**
             * @param weather The weather
             */
            public void setWeather(String weather) {
                this.weather = weather;
            }

            /**
             * @return The wind
             */
            public String getWind() {
                return wind;
            }

            /**
             * @param wind The wind
             */
            public void setWind(String wind) {
                this.wind = wind;
            }

            /**
             * @return The temperature
             */
            public String getTemperature() {
                return temperature;
            }

            /**
             * @param temperature The temperature
             */
            public void setTemperature(String temperature) {
                this.temperature = temperature;
            }

        }

    }


}

这是我的测试日志

10-02 10:41:54.687 31361-31361/messagelogix.com.mysandbox D/MainActivity: 用gson进行解析
10-02 10:41:54.820 31361-31361/package.com.mysandbox D/MainActivity: weatherInfo package.com.mysandbox.WeatherInfo@41469fa0
10-02 10:41:54.820 31361-31361/package.com.mysandbox D/MainActivity: error is 0
10-02 10:41:54.820 31361-31361/package.com.mysandbox D/MainActivity: status is success
10-02 10:41:54.820 31361-31361/package.com.mysandbox D/MainActivity: date is 2015-10-02
10-02 10:41:54.828 31361-31361/package.com.mysandbox D/MainActivity: currentcity is beijing

答案 1 :(得分:0)

在你的json中,index映射jsonarray,而不是jsonobject,但在Results类中,weather_data不是数组,因此存在Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 62 path $.results
要解决它,只需将weather_data转换为数组并为其修改getter和setter。