android Volley+Gson的使用

  听说Volley框架非常好用,今天试了一下post请求,果然如此,因为我传的是json获取的也是json所以就写了一种关于json的请求,其实其他的代码都差不多.首先要先创建一个全局的变量,请求入队列使用代码如下:

public class MyApplication extends Application{
    public static RequestQueue requestQueue;
    //public static Context context;
    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
     requestQueue=Volley.newRequestQueue(getApplicationContext());
    }

    public static RequestQueue getHttpRequestQueue(){
        return requestQueue;
    }
}

然后开始请求代码如下:

public class Volley {
    public String url="http://api.avatardata.cn/Joke/NewstJoke";
    String resultStr;
    Gson gson;
    public Volley(){
        volleyPost();
    }
    public void volleyPost(){
        StringRequest request=new StringRequest(Method.POST,url,new Listener<String>() {
            @Override
            public void onResponse(String response) {
                // TODO Auto-generated method stub
                //System.out.println(response.toString());
                resultStr=response.toString();
                Gson gson=new Gson();
                Idiom idiom=gson.fromJson(resultStr, Idiom.class);
                System.out.println(idiom);
            }
        }, new ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                // TODO Auto-generated method stub
            //    System.out.println(error.toString());
                resultStr=error.toString();
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                // TODO Auto-generated method stub
                Map<String,String> map=new HashMap<String, String>();
                map.put("key", "yourkey");
                map.put("dtype", "JSON");
                map.put("format", "true");
                map.put("page", "1");
                map.put("rows", "10");
                return map;
            }
            
        };
        MyApplication.getHttpRequestQueue().add(request);
    }
}

这样就可以轻松获取json数据。另外获取数据如何解析呢?  简单的json我们直接用android 里面的jsonObject就可以解决,但是稍微复杂一点,包含数组什么的那样的话会很麻烦,不要紧,可以用gson来进行json解析,就是把获取json串的字段全部封装到对象里面,遇到[ ]就用List,遇到{}就用对象来定义,一层层的封装,然后实例化gson,就可以很容易的获取到数据。

如下字符串,截取不完整:

好吧,就这样吧,需要代码的话可以找我。因为我比较懒,所以大家将就点吧,虽然不能看到详细的代码,但是方法还是很清楚的了解的。

 

一下是我封装的两个类

posted @ 2016-05-24 14:09  ZBB0304  阅读(1047)  评论(1编辑  收藏  举报