用Gson解析复杂的天气Json数据

对于结构简单的Json数据用android集成的JSONArray和JSONObject就可以解析出来,当遇到比较比较复杂的数据时可以考虑用Gson,最近刚好在做一个关于天气的app,要从如下Json数据中得到自己想要的数据。Json数据如下:

{
    "error_code":0,
    "reason":"成功",
    "result":{
        "sk":{
            "temp":"27",
            "wind_direction":"西南风",
            "wind_strength":"3级",
            "humidity":"44",
            "time":"19:42"
        },
        "today":{
            "city":"北京",
            "date_y":"2015年08月18日",
            "week":"星期二",
            "temperature":"20~30",
            "weather":"雷阵雨",
            "fa":"04",
            "fb":"21",
            "wind":"无持续风向 微风",
            "dressing_index":"热",
            "dressing_advice":"天气热,建议着短裙、短裤、短薄外套、T恤等夏季服装。",
            "uv_index":"弱",
            "comfort_index":"--",
            "wash_index":"不宜",
            "travel_index":"较不宜",
            "exercise_index":"较不宜",
            "drying_index":"--"
        },
        "future":[
            {
                "temperature":"20~28",
                "weather":"雷阵雨",
                "fa":"04",
                "fb":"04",
                "wind":"无持续风向 微风",
                "week":"星期三",
                "date":"20150819"
            },
            {
                "temperature":"22~33",
                "weather":"多云",
                "fa":"01",
                "fb":"01",
                "wind":"无持续风向 微风",
                "week":"星期四",
                "date":"20150820"
            },
            {
                "temperature":"21~31",
                "weather":"雷阵雨",
                "fa":"04",
                "fb":"04",
                "wind":"无持续风向 微风",
                "week":"星期五",
                "date":"20150821"
            },
            {
                "temperature":"20~29",
                "weather":"雷阵雨",
                "fa":"04",
                "fb":"03",
                "wind":"无持续风向 微风",
                "week":"星期六",
                "date":"20150822"
            },
            {
                "temperature":"20~28",
                "weather":"阵雨",
                "fa":"03",
                "fb":"03",
                "wind":"无持续风向 微风",
                "week":"星期日",
                "date":"20150823"
            },
            {
                "temperature":"20~29",
                "weather":"阴",
                "fa":"02",
                "fb":"02",
                "wind":"无持续风向 微风",
                "week":"星期一",
                "date":"20150824"
            }
        ]
    }
}

方法是写一个序列化的Bean类,需要注意以下几点

1、内部嵌套的类必须是static的,要不然解析会出错;
2、类里面的属性名必须跟Json字段里面的Key是一模一样的;
3、内部嵌套的用[]括起来的部分是一个List,所以定义为 public List b,而只用{}嵌套的就定义为 public C c。


根据上面Json数据最外层的的结构可分为三个对象error_code、reason、result,注意属性名和Json里是一样的:

public class Status {
    private Integer error_code;
    private String reason;
    private MyResult result;

    public Integer getError_code() {
        return error_code;
    }

    public void setError_code(Integer error_code) {
        this.error_code = error_code;
    }

    public String getReason() {
        return reason;
    }

    public void setReason(String reason) {
        this.reason = reason;
    }

    public MyResult getResult() {
        return result;
    }

    public void setResult(MyResult result) {
        this.result = result;
    }
}


其中result里还有两个对象Sk、today和一个数组future,数组用List集合包装起来:

public class MyResult {
    private MySk sk;
    private MyToday today;
    private List future;

    public MySk getSk() {
        return sk;
    }

    public void setSk(MySk sk) {
        this.sk = sk;
    }

    public MyToday getToday() {
        return today;
    }

    public void setToday(MyToday today) {
        this.today = today;
    }

    public List getFuture() {
        return future;
    }

    public void setFuture(List future) {
        this.future = future;
    }
}


如此类推,sk类

public class MySk {
    private String temp;
    private String wind_direction;
    private String wind_strength;
    private String humidity;
    private String time;

    public String getTemp() {
        return temp;
    }

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

    public String getWind_direction() {
        return wind_direction;
    }

    public void setWind_direction(String wind_direction) {
        this.wind_direction = wind_direction;
    }

    public String getWind_strength() {
        return wind_strength;
    }

    public void setWind_strength(String wind_strength) {
        this.wind_strength = wind_strength;
    }

    public String getHumidity() {
        return humidity;
    }

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

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }
}

today类:

public class MyToday {
    private String city;
    private String date_y;
    private String week;
    private String temperature;
    private String weather;
    private String fa;
    private String fb;
    private String wind;
    private String dressing_index;
    private String dressing_advice;
    private String uv_index;
    private String comfort_index;
    private String wash_index;
    private String travel_index;
    private String exercise_index;
    private String drying_index;

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getDate_y() {
        return date_y;
    }

    public void setDate_y(String date_y) {
        this.date_y = date_y;
    }

    public String getWeek() {
        return week;
    }

    public void setWeek(String week) {
        this.week = week;
    }

    public String getTemperature() {
        return temperature;
    }

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

    public String getWeather() {
        return weather;
    }

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

    public String getFa() {
        return fa;
    }

    public void setFa(String fa) {
        this.fa = fa;
    }

    public String getFb() {
        return fb;
    }

    public void setFb(String fb) {
        this.fb = fb;
    }

    public String getWind() {
        return wind;
    }

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

    public String getDressing_index() {
        return dressing_index;
    }

    public void setDressing_index(String dressing_index) {
        this.dressing_index = dressing_index;
    }

    public String getDressing_advice() {
        return dressing_advice;
    }

    public void setDressing_advice(String dressing_advice) {
        this.dressing_advice = dressing_advice;
    }

    public String getUv_index() {
        return uv_index;
    }

    public void setUv_index(String uv_index) {
        this.uv_index = uv_index;
    }

    public String getComfort_index() {
        return comfort_index;
    }

    public void setComfort_index(String comfort_index) {
        this.comfort_index = comfort_index;
    }

    public String getWash_index() {
        return wash_index;
    }

    public void setWash_index(String wash_index) {
        this.wash_index = wash_index;
    }

    public String getTravel_index() {
        return travel_index;
    }

    public void setTravel_index(String travel_index) {
        this.travel_index = travel_index;
    }

    public String getExercise_index() {
        return exercise_index;
    }

    public void setExercise_index(String exercise_index) {
        this.exercise_index = exercise_index;
    }

    public String getDrying_index() {
        return drying_index;
    }

    public void setDrying_index(String drying_index) {
        this.drying_index = drying_index;
    }
}

future类:

public class MyFuture {
    private String temperature;
    private String weather;
    private String fa;
    private String fb;
    private String wind;
    private String week;
    private String date;

    public String getTemperature() {
        return temperature;
    }

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

    public String getWeather() {
        return weather;
    }

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

    public String getFa() {
        return fa;
    }

    public void setFa(String fa) {
        this.fa = fa;
    }

    public String getFb() {
        return fb;
    }

    public void setFb(String fb) {
        this.fb = fb;
    }

    public String getWind() {
        return wind;
    }

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

    public String getWeek() {
        return week;
    }

    public void setWeek(String week) {
        this.week = week;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }
}

这样就完成了全部Bean类的编码,然后是如何解析自己想要的数据,其中的Gson和Volley要导入jar包,主界面是一个Button和一个Testview,点击按钮加载自己要的数据并显示,不要忘了在Manifest中加入internet的权限

public class MainActivity extends AppCompatActivity {

    private TextView textView;
    private RequestQueue queue;
    private Button button;
    private Gson gson;
    private String url;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Volley实例化
        queue = Volley.newRequestQueue(this);
        textView = (TextView) findViewById(R.id.content_text);
        button = (Button) findViewById(R.id.button);

        gson = new Gson();

        try {
            //这个URL是自己在网上申请的一个天气接口
            String addressCode = URLEncoder.encode("北京", "UTF-8");
            url = "http://apis.haoservice.com/weather?cityname=" + addressCode + "&key=b2827fdb1ceb477684fdd442b0100fa9";
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //Volley的StringRequest方法
        final StringRequest stringRequest = new StringRequest(url,
                new Response.Listener() {
                    @Override
                    public void onResponse(String s) {
                        if (!TextUtils.isEmpty(s)) {
                            Log.d("TAG", s);
                            System.out.println(s);
                            Status status = gson.fromJson(s, Status.class);
                            MyResult myResult = status.getResult();
                            MyToday myToday = myResult.getToday();
                            //这是我想要得到的数据城市+日期+温度+天气情况+穿衣建议
                            String msg = myToday.getCity() + myToday.getDate_y() + myToday.getTemperature() + myToday.getWeather() + "\n" + myToday.getDressing_advice();
                            textView.setText(msg);
                        } else {
                            Toast.makeText(MainActivity.this, "加载失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.e("TAG", volleyError.getMessage(), volleyError);
            }
        });

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击触发下载
                queue.add(stringRequest);

            }
        });

    }

}


结果如下
用Gson解析复杂的天气Json数据_第1张图片




你可能感兴趣的:(用Gson解析复杂的天气Json数据)