android volley json

Android Volley中Json用法总结


Volley基本用法:

创建一个RequestQueue对象;
创建JsonObjectRequest对象;
将jsonObjectRequest添加到requestQueue中;

举例:

RequestQueue mQueue = Volley.newRequestQueue(context);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest

("http://m.weather.com.cn/data/101010100.html", null,  
        new Response.Listener() {  
            @Override  
            public void onResponse(JSONObject response) {  
                Log.d("TAG", response.toString());  
            }  
        }, new Response.ErrorListener() {  
            @Override  
            public void onErrorResponse(VolleyError error) {  
                Log.e("TAG", error.getMessage(), error);  
            }  
        });  
mQueue.add(jsonObjectRequest);

Gson基本用法:
gson-2.2.4.jar

Gson提供了fromJson()和toJson() 两个直接用于解析和生成的方法,前者实现反序列化,后者实现了序列化。

Class User {
    String name;
    int age;
    
    User(String name, int age) {
        this.name = name;
        this.name = age;
    }
}

Gson gson = new Gson();

User user = new User("xiaoming", "10");
String jsonObject = gson.toJson(user);
System.out.println(jsonObject);

User user2 = gson.fromJson(jsonObject, User.class);
System.out.println(user2.name);

第一个输出 {"name":"xiaoming", "age":"10"}
第二个输出 xiaoming

List解析:
User user1 = new User("aaa", "11");
User user2 = new User("bbb", "22");
List list  = new ArrayList();
list.add(user1);
list.add(user2);
String string = gson.toJson(list);

List fromList = gson.fromJson(string, new TypeToken>(){}.getType());
for (User user : fromList) {
System.out.println(user.name);
}

输出aaa bbb

GsonBuilder基本用法:

Gson gson = new GsonBuilder()
               //各种配置
               .create(); //生成配置好的Gson
Gson gson = new GsonBuilder()
        //序列化null
        .serializeNulls()
        // 设置日期时间格式,另有2个重载方法
        // 在序列化和反序化时均生效
        .setDateFormat("yyyy-MM-dd")
        // 禁此序列化内部类
        .disableInnerClassSerialization()
        //生成不可执行的Json(多了 )]}' 这4个字符)
        .generateNonExecutableJson()
        //禁止转义html标签
        .disableHtmlEscaping()
        //格式化输出
        .setPrettyPrinting()
        .create();


自定义Request:

public class GsonRequest extends Request {
    private final Gson gson = new Gson();
    private final Class clazz;
    private final Map headers;
    private final Listener listener;

    public GsonRequest(String url, Class clazz, Map headers,
            Listener listener, ErrorListener errorListener) {
        super(Method.GET, url, errorListener);
        this.clazz = clazz;
        this.headers = headers;
        this.listener = listener;
    }
 
    @Override
    public Map getHeaders() throws AuthFailureError {
        return headers != null ? headers : super.getHeaders();
    }
 
    @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));
        }
    }
}

继承了Request中的三个方法:

deliverResponse() : mListener中的onResponse()方法,并将response内容传入,将服务器响应的数据进行回调了;


parseNetworkResponse() : 对服务器响应的数据进行解析,其中数据是以字节的形式存放在NetworkResponse的data变量中的,将数据取出然后组装成一个String,并传入Response的success()方法中;


getHeaders():请求附带的头信息;





你可能感兴趣的:(android)