客户端跟服务器交互的时候我们使用json实现 但是 在交互的时候除了传送json对象数据意外 我们还需要传输标志位等
比如我们现在的交互方式格式
对象
{
"data": {
"age": 29,
"name": "wangzhiqiang",
"sex": 1
},
"message": "ok",
"status": 200
}
列表
{
"data": [
{
"age": 29,
"name": "wangzhiqiang",
"sex": 1
},
{
"age": 29,
"name": "wangzhiqiang",
"sex": 1
}
],
"message": "ok",
"status": 200
}
出错
{
"message": "用户密码不正确!",
"status": 355
}
http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/index.html
JsonParser 解析json文本的解析器,它将json文本解析成JsonElement树。
JsonElement 用来表示一个json元素的类,它可能是JsonObject,JsonArray,JsonPrimitive,JsonNull.
这样我们就可以首先解析跟服务器预定的交互格式了demo:
try {
String json = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
// #1 解析code message code=200&& message="ok"代表成功
JsonPraser parser = new JsonParser();
JsonObject root = parser.parse(json).getAsJsonObject();
int code = root.get("code").getAsInt();
String message = root.get("message").getAsString();
if (code == HttpStatus.SC_OK) {// 操作成功
return parseNetworkResponse(root, response);
} else {
return Response.error(new NetError(code, message));
}
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (com.google.gson.JsonSyntaxException e) {
return Response.error(new ParseError(e));
}
主要源码(请求使用volley):
public abstract class DRequest<T> extends Request<T> {
protected String KEY_CONTENT = "content";
protected String KEY_DATA = "data";
Map<String, String> mParams;
public DRequest(String url,ErrorListener errorListener) {
this(Method.POST, url,new HashMap<String, String>(),errorListener);
}
public DRequest(String url,Map<String, String> params,ErrorListener errorListener) {
this(Method.POST, url,params,errorListener);
}
public DRequest(int method, String url,Map<String, String> params,ErrorListener errorListener) {
super(method, url, errorListener);
this.mParams = params;
}
@Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
String json = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
// #1 解析code message code=200&& message="ok"代表成功
JsonParser parser = new JsonParser();
JsonObject root = parser.parse(json).getAsJsonObject();
int code = root.get("code").getAsInt();
String message = root.get("message").getAsString();
if (code == HttpStatus.SC_OK) {// 操作成功
return parseNetworkResponse(root, response);
} else {
return Response.error(new NetError(code, message));
}
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (com.google.gson.JsonSyntaxException e) {
return Response.error(new ParseError(e));
}
}
@Override
public Map<String, String> getParams() throws AuthFailureError {
return mParams;
}
public void put(String key, String value) {
mParams.put(key, value);
}
/**
* 子类实现解析
*
* @param root
* @param response
* @return
*/
public abstract Response<T> parseNetworkResponse(JsonObject root,
NetworkResponse response);
}
public class DJsonRequest<T> extends DRequest<DataContainer<T>> {
private Type type;
private RequestHandler<T> handler;
public DJsonRequest(String url,RequestHandler<T> handler, Type type) {
super(url, handler);
this.type = type;
this.handler =handler;
}
public DJsonRequest(int method, String url,
Map<String, String> params, RequestHandler<T> handler, Type type) {
super(method,url, params,handler);
this.type = type;
this.handler =handler;
}
@Override
public Response<DataContainer<T>> parseNetworkResponse(JsonObject root,
NetworkResponse response) {
Log.d("MyNet","获得响应");
// data 元素
JsonElement dataElement = root.get(KEY_DATA);
if (dataElement.isJsonNull()) {// 不存在数据
return Response.error(new NetError(703, "data空!"));
}
JsonObject data = dataElement.getAsJsonObject();
JsonElement contentElement = data.get(KEY_CONTENT);
if (contentElement.isJsonNull()) {// content 里面是null
return Response.error(new NetError(702, "content空!"));
}
if (contentElement.isJsonObject()) {// conatent里面是对象
T result = new Gson().fromJson(contentElement, type);
DataContainer<T> container = new DataContainer<T>();
container.dataSingle = result;
return Response.success(container,
HttpHeaderParser.parseCacheHeaders(response));
}
if (contentElement.isJsonArray()) {// 数组
List<T> list = new Gson().fromJson(contentElement, type);
DataContainer<T> container = new DataContainer<T>();
container.dataList = list;
return Response.success(container,
HttpHeaderParser.parseCacheHeaders(response));
}
return Response.error(new NetError(703, "data空!"));
}
@Override
protected void deliverResponse(DataContainer<T> response) {
if (handler!=null) {
handler.onResponse(response);
}
}
}
注意(我的json格式中有content元素 )
现在我们直接解析data元素了 嬷嬷哒~