Gson实现自定义解析json格式

客户端跟服务器交互的时候我们使用json实现 但是 在交互的时候除了传送json对象数据意外 我们还需要传输标志位等

比如我们现在的交互方式格式

对象
  1. {
  2. "data": {
  3. "age": 29,
  4. "name": "wangzhiqiang",
  5. "sex": 1
  6. },
  7. "message": "ok",
  8. "status": 200
  9. }
列表
  1. {
  2. "data": [
  3. {
  4. "age": 29,
  5. "name": "wangzhiqiang",
  6. "sex": 1
  7. },
  8. {
  9. "age": 29,
  10. "name": "wangzhiqiang",
  11. "sex": 1
  12. }
  13. ],
  14. "message": "ok",
  15. "status": 200
  16. }
出错
  1. {
  2. "message": "用户密码不正确!",
  3. "status": 355
  4. }

http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/index.html


JsonParser  解析json文本的解析器,它将json文本解析成JsonElement树。

JsonElement 用来表示一个json元素的类,它可能是JsonObject,JsonArray,JsonPrimitive,JsonNull.

这样我们就可以首先解析跟服务器预定的交互格式了demo:

  1. try {
  2. String json = new String(response.data,
  3. HttpHeaderParser.parseCharset(response.headers));
  4. // #1 解析code message code=200&& message="ok"代表成功
  5. JsonPraser parser = new JsonParser();
  6. JsonObject root = parser.parse(json).getAsJsonObject();
  7. int code = root.get("code").getAsInt();
  8. String message = root.get("message").getAsString();
  9. if (code == HttpStatus.SC_OK) {// 操作成功
  10. return parseNetworkResponse(root, response);
  11. } else {
  12. return Response.error(new NetError(code, message));
  13. }
  14. } catch (UnsupportedEncodingException e) {
  15. return Response.error(new ParseError(e));
  16. } catch (com.google.gson.JsonSyntaxException e) {
  17. return Response.error(new ParseError(e));
  18. }
主要源码(请求使用volley):
  1. public abstract class DRequest<T> extends Request<T> {
  2. protected String KEY_CONTENT = "content";
  3. protected String KEY_DATA = "data";
  4. Map<String, String> mParams;
  5. public DRequest(String url,ErrorListener errorListener) {
  6. this(Method.POST, url,new HashMap<String, String>(),errorListener);
  7. }
  8. public DRequest(String url,Map<String, String> params,ErrorListener errorListener) {
  9. this(Method.POST, url,params,errorListener);
  10. }
  11. public DRequest(int method, String url,Map<String, String> params,ErrorListener errorListener) {
  12. super(method, url, errorListener);
  13. this.mParams = params;
  14. }
  15. @Override
  16. protected Response<T> parseNetworkResponse(NetworkResponse response) {
  17. try {
  18. String json = new String(response.data,
  19. HttpHeaderParser.parseCharset(response.headers));
  20. // #1 解析code message code=200&& message="ok"代表成功
  21. JsonParser parser = new JsonParser();
  22. JsonObject root = parser.parse(json).getAsJsonObject();
  23. int code = root.get("code").getAsInt();
  24. String message = root.get("message").getAsString();
  25. if (code == HttpStatus.SC_OK) {// 操作成功
  26. return parseNetworkResponse(root, response);
  27. } else {
  28. return Response.error(new NetError(code, message));
  29. }
  30. } catch (UnsupportedEncodingException e) {
  31. return Response.error(new ParseError(e));
  32. } catch (com.google.gson.JsonSyntaxException e) {
  33. return Response.error(new ParseError(e));
  34. }
  35. }
  36. @Override
  37. public Map<String, String> getParams() throws AuthFailureError {
  38. return mParams;
  39. }
  40. public void put(String key, String value) {
  41. mParams.put(key, value);
  42. }
  43. /**
  44. * 子类实现解析
  45. *
  46. * @param root
  47. * @param response
  48. * @return
  49. */
  50. public abstract Response<T> parseNetworkResponse(JsonObject root,
  51. NetworkResponse response);
  52. }
  1. public class DJsonRequest<T> extends DRequest<DataContainer<T>> {
  2. private Type type;
  3. private RequestHandler<T> handler;
  4. public DJsonRequest(String url,RequestHandler<T> handler, Type type) {
  5. super(url, handler);
  6. this.type = type;
  7. this.handler =handler;
  8. }
  9. public DJsonRequest(int method, String url,
  10. Map<String, String> params, RequestHandler<T> handler, Type type) {
  11. super(method,url, params,handler);
  12. this.type = type;
  13. this.handler =handler;
  14. }
  15. @Override
  16. public Response<DataContainer<T>> parseNetworkResponse(JsonObject root,
  17. NetworkResponse response) {
  18. Log.d("MyNet","获得响应");
  19. // data 元素
  20. JsonElement dataElement = root.get(KEY_DATA);
  21. if (dataElement.isJsonNull()) {// 不存在数据
  22. return Response.error(new NetError(703, "data空!"));
  23. }
  24. JsonObject data = dataElement.getAsJsonObject();
  25. JsonElement contentElement = data.get(KEY_CONTENT);
  26. if (contentElement.isJsonNull()) {// content 里面是null
  27. return Response.error(new NetError(702, "content空!"));
  28. }
  29. if (contentElement.isJsonObject()) {// conatent里面是对象
  30. T result = new Gson().fromJson(contentElement, type);
  31. DataContainer<T> container = new DataContainer<T>();
  32. container.dataSingle = result;
  33. return Response.success(container,
  34. HttpHeaderParser.parseCacheHeaders(response));
  35. }
  36. if (contentElement.isJsonArray()) {// 数组
  37. List<T> list = new Gson().fromJson(contentElement, type);
  38. DataContainer<T> container = new DataContainer<T>();
  39. container.dataList = list;
  40. return Response.success(container,
  41. HttpHeaderParser.parseCacheHeaders(response));
  42. }
  43. return Response.error(new NetError(703, "data空!"));
  44. }
  45. @Override
  46. protected void deliverResponse(DataContainer<T> response) {
  47. if (handler!=null) {
  48. handler.onResponse(response);
  49. }
  50. }
  51. }
注意(我的json格式中有content元素 )



现在我们直接解析data元素了  嬷嬷哒~










上一篇:用python库openpyxl操作excel,从源excel表中提取信息复制到目标excel表中


下一篇:深入理解JVM(6)——JVM性能调优实战