【第四篇】Volley修改之GsonRequest

json解析工具类的引入,这里引用lite马天宇的解析json的工具类:

public class GsonImpl extends Json {
    private Gson gson = new Gson();

    @Override
    public String toJson(Object src) {
        return gson.toJson(src);
    }

    @Override
    public <T> T toObject(String json, Class<T> claxx) {
        return gson.fromJson(json, claxx);
    }

    @Override
    public <T> T toObject(byte[] bytes, Class<T> claxx) {
        return gson.fromJson(new String(bytes), claxx);
    }

}
public abstract class Json {
    private static Json json;

    Json() {}

    public static Json get() {
        if (json == null) {
            json = new GsonImpl();
        }
        return json;
    }

    public abstract String toJson(Object src);

    public abstract <T> T toObject(String json, Class<T> claxx);

    public abstract <T> T toObject(byte[] bytes, Class<T> claxx);
}

集成子Request,在parseNetworkResponse方法里面封装解析json的逻辑

public class GsonRequest<T> extends Request<T> {
    private Class<T> mClazz;
    private Listener<T> listener;
    private Map<String, String> headers;

    /**
     * 
     * @param method
     *            請求方式
     * @param url
     *            获取json的url
     * @param clazz
     *            json对应的javaBean
     * @param headers
     *            头文件
     * @param listener
     *            监听
     * @param errorListener
     *            错误监听
     */

    public GsonRequest(int method, String url, Class<T> clazz,
            Map<String, String> headers, Listener<T> listener,
            ErrorListener errorListener) {
        super(method, url, errorListener);
        this.mClazz = clazz;
        this.headers = headers;
        this.listener = listener;
    }

    /**
     * 获取头文件
     */
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        return headers != null ? headers : super.getHeaders();
    }

    /**
     * 解析json
     */
    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        String jsonString;
        try {
            jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers));
            return Response.success(
                    GsonImpl.get().toObject(jsonString, mClazz),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        }
    }

    /**
     * 分发返回内容
     */
    @Override
    protected void deliverResponse(T response) {
        listener.onResponse(response);
    }
}

使用demo:

1 ,添加网络权限;

2,编码:

http://www.weather.com.cn/data/sk/101010100.html里面的json数据如下:

{"weatherinfo":{"city":"北京","cityid":"101010100","temp":"9","WD":"西南风","WS":"2级","SD":"22%","WSE":"2","time":"10:45","isRadar":"1","Radar":"JC_RADAR_AZ9010_JB","njd":"暂无实况","qy":"1014"}}

对应的javaBean为如下两个类:

public class Weather implements Serializable{
    private static final long serialVersionUID = 1L;
    private Weatherinfo weatherinfo;  
      
    public Weatherinfo getWeatherinfo() {  
        return weatherinfo;  
    }  
  
    public void setWeatherinfo(Weatherinfo weatherinfo) {  
        this.weatherinfo = weatherinfo;  
    }

    @Override
    public String toString() {
        return "Weather [weatherinfo=" + weatherinfo + "]";
    }  
}

 

和Weatherinfo类:

public class Weatherinfo implements Serializable{

    private static final long serialVersionUID = 1L;
    private String city;
    private String cityid;
    private String temp;
    private String WD;
    private String WS;
    private String SD;
    private String WSE;
    private String time;
    private String isRadar;
    private String Radar;
    private String njd;
    private String qy;

    public String getCity() {
        return city;
    }

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

    public String getCityid() {
        return cityid;
    }

    public void setCityid(String cityid) {
        this.cityid = cityid;
    }

    public String getTemp() {
        return temp;
    }

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

    public String getWD() {
        return WD;
    }

    public void setWD(String wD) {
        WD = wD;
    }

    public String getWS() {
        return WS;
    }

    public void setWS(String wS) {
        WS = wS;
    }

    public String getSD() {
        return SD;
    }

    public void setSD(String sD) {
        SD = sD;
    }

    public String getWSE() {
        return WSE;
    }

    public void setWSE(String wSE) {
        WSE = wSE;
    }

    public String getTime() {
        return time;
    }

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

    public String getIsRadar() {
        return isRadar;
    }

    public void setIsRadar(String isRadar) {
        this.isRadar = isRadar;
    }

    public String getRadar() {
        return Radar;
    }

    public void setRadar(String radar) {
        Radar = radar;
    }

    public String getNjd() {
        return njd;
    }

    public void setNjd(String njd) {
        this.njd = njd;
    }

    public String getQy() {
        return qy;
    }

    public void setQy(String qy) {
        this.qy = qy;
    }

    @Override
    public String toString() {
        return "Weatherinfo [city=" + city + ", cityid=" + cityid + ", temp="
                + temp + ", WD=" + WD + ", WS=" + WS + ", SD=" + SD + ", WSE="
                + WSE + ", time=" + time + ", isRadar=" + isRadar + ", Radar="
                + Radar + ", njd=" + njd + ", qy=" + qy + "]";
    }

}

Activity里面:

public class MainActivity extends Activity {
    private String url = "http://www.weather.com.cn/data/sk/101010100.html";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RequestQueue mQueue = Volley.newRequestQueue(this);
        GsonRequest<Weather> request = new GsonRequest<Weather>(Method.GET, url, Weather.class, null, new Response.Listener<Weather>() {

            @Override
            public void onResponse(Weather response) {
                Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
        mQueue.add(request);
        
    }
}

 

转载于:https://www.cnblogs.com/androidsuperman/p/4786330.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值