舌尖上的Android Volley(二)

经过上一篇文章的学习,我们已经品尝了Volley的Request的StringRequest、JsonRequest、ImageRequest、ImageLoader、NetworkImageView等几种美食。其中StringRequest用于请求普通的文本数据,JsonRequest(JsonObjectRequest、JsonArrayRequest)用于请求JSON格式的数据,ImageRequest、ImageLoader和NetworkImageView都是用于请求下载网络图片的。如果你还没有品尝这几种美食,建议你先去尝一尝上一篇文章的美食《舌尖上的Android Volley(一)》

“在繁华的城市里,生活着一群程序猿们,他们运用各自智慧,适度、巧妙的利用Volley提供的Request,获得质朴美味的食物……”

JsonRequest的数据解析是利用Android本身自带的JSONObject和JSONArray来实现的。不过,当我们使用JSONObject解析数据时还是比较麻烦,当你想到可以使用GSON,FastJson等工具时,然而Volley中默认并不支持使用GSON来解析数据。为了满足各位食客的挑剔,我们自定义一个GsonRequest来满足你的味蕾。

自定义GsonRequest

  • 实现一个request时必须继承Request类,表示request期望解析的response的类型,比如解析的response是字符串,则创建自定义的request通过继承Request

  • parseNetworkResponse
    在parseNetworkResponse()方法中,先是将服务器响应的数据解析出来,然后通过调用Gson的fromJson方法将数据组装成Response类使用给定的类型对象,用于传递。

  • deliverResponse
    Volley将parseNetworkResponse()中返回的对象传递到主线程,当发起请求时会在此调用回调接口。

下面我们以http://www.tngou.net/tnfs/api/classify为例,用我们自定义的GsonRequest获取下面的数据并解析。

{"status":true,"tngou":[{"description":"性感美女","id":1,"keywords":"性感美女","name":"性感美女","seq":1,"title":"性感美女"},{"description":"韩日美女","id":2,"keywords":"韩日美女","name":"韩日美女","seq":2,"title":"韩日美女"},{"description":"丝袜美腿","id":3,"keywords":"丝袜美腿","name":"丝袜美腿","seq":3,"title":"丝袜美腿"},{"description":"美女照片","id":4,"keywords":"美女照片","name":"美女照片","seq":4,"title":"美女照片"},{"description":"美女写真","id":5,"keywords":"美女写真","name":"美女写真","seq":5,"title":"美女写真"},{"description":"清纯美女","id":6,"keywords":"清纯美女","name":"清纯美女","seq":6,"title":"清纯美女"},{"description":"性感车模","id":7,"keywords":"性感车模","name":"性感车模","seq":7,"title":"性感车模"}]}

GsonRequest.java

public class GsonRequest<T> extends Request<T> {

    private final Gson gson = new Gson();
    private final Class clazz;
    private final Response.Listener listener;

    public GsonRequest(String url, Class clazz, Response.Listener listener, Response.ErrorListener errorListener) {
        super(Method.GET, url, errorListener);
        this.clazz = clazz;
        this.listener = listener;
    }

    @Override
    protected void deliverResponse(T response) {
        listener.onResponse(response);
    }

    @Override
    protected Response parseNetworkResponse(NetworkResponse response) {
        try {
            String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            return Response.success(gson.fromJson(json, clazz), HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JsonSyntaxException e) {
            return Response.error(new ParseError(e));
        }
    }
}

新建一个BelleRoot类解析json数据

public class BelleRoot {

    private boolean status;

    private List tngou;

    public boolean isStatus() {
        return status;
    }

    public void setStatus(boolean status) {
        this.status = status;
    }

    public List getTngou() {
        return tngou;
    }

    public void setTngou(List tngou) {
        this.tngou = tngou;
    }

    public static class TngouBean {
        private String description;
        private int id;
        private String keywords;
        private String name;
        private int seq;
        private String title;

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getKeywords() {
            return keywords;
        }

        public void setKeywords(String keywords) {
            this.keywords = keywords;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getSeq() {
            return seq;
        }

        public void setSeq(int seq) {
            this.seq = seq;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }
    }
}

下面我们在Activity类中调用GsonRequest,代码比较简单就不再细说。

public class MainActivity extends AppCompatActivity {

    private RequestQueue mRequestQueue;
    private List list = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mRequestQueue = Volley.newRequestQueue(this);

        GsonRequest gsonRequest = new GsonRequest(
                "http://www.tngou.net/tnfs/api/classify", BelleRoot.class,
                new Response.Listener() {
                    @Override
                    public void onResponse(BelleRoot belle) {
                        list.addAll(belle.getTngou());
                        for (int i = 0; i < list.size(); i++) {
                            Log.d("TAG", list.get(i).getTitle());
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("TAG", error.getMessage(), error);
            }
        });
        mRequestQueue.add(gsonRequest);
    }
}

各位程序猿(媛)吃货们,菜出锅啦!
舌尖上的Android Volley(二)_第1张图片

注意

  • 别忘了在AndroidManifest.xml里声明网络权限。
<uses-permission android:name="android.permission.INTERNET"/>
  • 在build.gradle中添加volley和gson依赖。
compile 'com.mcxiaoke.volley:library:1.0.19'
compile 'com.google.code.gson:gson:2.2.4'

最后为各位看官奉上Demo源码,点击下载。

你可能感兴趣的:(Android)