使用Volley请求数据,并使用Gson解析(解决请求来的数据乱码问题)

前言:最近一直想做一个关于天气的app,因为刚接触Android,做起来还是有点吃力的。所以记录一下数据请求这一块遇到的问题。


首先请求数据:天气接口http://wthrcdn.etouch.cn/weather_mini?citykey=101010100


下载volley.jar,放到项目的lib目录下:F:\AndroidApp\NetWorkDemo\app\libs这是我本地的目录。然后重新编译gradle,就可以使用了。如果不可以看一下项目的build.gradle下面是否有如下代码:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.1.1'
}


我现在用的是StringRequest所以这里先说StringRequest:

首先需要获取到一个RequestQueue对象:

mQueue = Volley.newRequestQueue(this);

 
 这是一个请求队列可以缓存所有的HTTP请求,并按一定顺序发出。 
 RequestQueue内部的设计就是非常合适高并发的,因此我们不必为每一次HTTP请求都创建一个RequestQueue对象,这是非常浪费资源的,基本上在每一个需要和网络交互的Activity中创建一个RequestQueue对象就足够了。 
 

接下来为了要发出一条HTTP请求,我们还需要创建一个StringRequest对象,如下所示:

private void Requese(){
    stringRequest = new StringRequest("http://wthrcdn.etouch.cn/weather_mini?citykey=101010100",
            new Response.Listener<String>()
        {
            @Override
            public void onResponse(String response)
            {
                /**  * 由于Volley是用的ISO-8859-1编码,这里需要把字符串转换为utf-8编码。  * 不然会出现乱码。这个乱码跟AndroidStudio中的乱码还不一样。  */  try {
                    str = new String (response.getBytes("ISO-8859-1"),"utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

                /**  * 利用Gson解析获取下来的字符串,这里定义了四各类,WeatherData_TotalWeatherDataFutureDataPreviewsData  */  WeatherData_Total data = gson.fromJson(str, WeatherData_Total.class);
                WeatherData weather_data = data.getData();

                ArrayList<FutureData> future_data = (ArrayList<FutureData>) weather_data.getForecast();
                tv.setText(future_data.get(0).getFengxiang());
                try {
                    JSONObject jsObj = new JSONObject(str);
                    String weatherData_str =  jsObj.getString("data");
                    WeatherData weatherData = gson.fromJson(weatherData_str,WeatherData.class);
                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }
        },
        new Response.ErrorListener()
        {
            @Override
            public void onErrorResponse(VolleyError error)
            {
                Log.e("TAG", error.getMessage(), error);
            }

        });
}

 
 

这个StringRequest的构造函数需要传入三个参数,第一个参数就是目标服务器的URL地址,第二个参数是服务器响应成功的回调,第三个参数是服务器响应失败的回调。响应成功的回调里打印出服务器返回的内容,在响应失败的回调里打印出失败的详细信息。

最后将这个StringRequest对象添加到RequestQueue里,如下:

mQueue.add(stringRequest);

 
 

然后是请求来的json 的数据格式:

{
  "desc": "OK",
  "status": 1000,
  "data": {
    "wendu": "22",
    "ganmao": "风较大,较易发生感冒,注意防护。",
    "forecast": [
      {
        "fengxiang": "北风",
        "fengli": "5-6",
        "high": "高温 24",
        "type": "",
        "low": "低温 11",
        "date": "3日星期六"
      },
      {
        "fengxiang": "北风",
        "fengli": "4-5",
        "high": "高温 19",
        "type": "",
        "low": "低温 8",
        "date": "4日星期日"
      },
      {
        "fengxiang": "无持续风向",
        "fengli": "微风",
        "high": "高温 21",
        "type": "",
        "low": "低温 9",
        "date": "5日星期一"
      },
      {
        "fengxiang": "无持续风向",
        "fengli": "微风",
        "high": "高温 21",
        "type": "多云",
        "low": "低温 10",
        "date": "6日星期二"
      },
      {
        "fengxiang": "无持续风向",
        "fengli": "微风",
        "high": "高温 24",
        "type": "",
        "low": "低温 12",
        "date": "7日星期三"
      },
      {
        "fengxiang": "无持续风向",
        "fengli": "微风",
        "high": "高温 23",
        "type": "",
        "low": "低温 11",
        "date": "8日星期四"
      }
    ],
    "yesterday": {
      "fl": "微风",
      "fx": "无持续风向",
      "high": "高温 23",
      "type": "",
      "low": "低温 12",
      "date": "2日星期五"
    },
    "aqi": "59",
    "city": "北京"
  }
}


然后就是怎么解析这一份数据了,我参考的这位大兄弟的:http://www.jianshu.com/p/3b8ef7162e69,写的很详细。所以也就照猫画虎来了一套。

首先也是下载Gson.jar,自行百度,或者去上边的博客下。

然后就是构建对应的json结构的类。用的过程中发现一个取巧的方式,在线生成,避免了错误,简化工作!推荐:http://www.jsonschema2pojo.org/在线的工具,json转换成javaclass。

导入jar,然后就可以解析了。解析代码上边有了,这里单独提出来看一下:

WeatherData_Total data = gson.fromJson(str, WeatherData_Total.class);

WeatherData_Total对应的是json文件的整体结构,看一下WeatherData_Total的代码:

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

public class WeatherData_Total {
    private String desc;
    private String status;
    private WeatherData data;
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();


    public String getDesc() {
        return desc;
    }
    public void getDesc(String desc) {
        this.desc = desc;
    }

    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }

    public WeatherData getData() {
        return data;
    }
    public void setData(WeatherData data) {
        this.data = data;
    }

    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }
    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }

}

WeatherData对应的是json中data的数据,下面是WeatherData的代码:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WeatherData {

    private String wendu;
    private String ganmao;
    private String aqi;
    private String city;
    private List<FutureData> forecast = new ArrayList<FutureData>();
    private PreviewsData yesterday;
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    public String getWendu() {
        return wendu;
    }
    public void setWendu(String wendu) {
        this.wendu = wendu;
    }

    public String getGanmao() {
        return ganmao;
    }
    public void setGanmao(String ganmao) {
        this.ganmao = ganmao;
    }

    public String getAqi() {
        return aqi;
    }
    public void setAqi(String aqi) {
        this.aqi = aqi;
    }

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

    public List<FutureData> getForecast() {
        return forecast;
    }
    public void setForecast(List<FutureData> forecast) {
        this.forecast = forecast;
    }


    public PreviewsData getYesterday() {
        return yesterday;
    }
    public void setYesterday(PreviewsData yesterday) {
        this.yesterday = yesterday;
    }

    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }
    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }
}

可以看到json中forecast是一个jsonArray,所以这个属性声明成一个ArrayList,然后每一个子元素对应的是PriviewsData中的数据:

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

public class PreviewsData {
    private String fl;
    private String fx;
    private String high;
    private String type;
    private String low;
    private String date;
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    public String getFl() {
        return fl;
    }
    public void setFl(String fl) {
        this.fl = fl;
    }

    public String getFx() {
        return fx;
    }
    public void setFx(String fx) {
        this.fx = fx;
    }

    public String getHigh() {
        return high;
    }
    public void setHigh(String high) {
        this.high = high;
    }

    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }

    public String getLow() {
        return low;
    }
    public void setLow(String low) {
        this.low = low;
    }

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

    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }

}

FutureData:

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

public class FutureData {

    private String fengxiang;
    private String fengli;
    private String high;
    private String type;
    private String low;
    private String date;
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    public String getFengxiang() {
        return fengxiang;
    }
    public void setFengxiang(String fengxiang) {
        this.fengxiang = fengxiang;
    }

    public String getFengli() {
        return fengli;
    }
    public void setFengli(String fengli) {
        this.fengli = fengli;
    }

    public String getHigh() {
        return high;
    }
    public void setHigh(String high) {
        this.high = high;
    }

    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }

    public String getLow() {
        return low;
    }
    public void setLow(String low) {
        this.low = low;
    }

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

    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }
}


你可能感兴趣的:(android,网络,gson)