Gson解析空字符串发生异常的处理方法
2016-11-05 08:40
405 查看
前言
在实际开发项目中,服务器经常会用空字符串 “” 作为返回结果表示空值 ,但这在Gson当中就会遇到问题,如果这项数据的类型不是字符串,Gson解析就会报错
Json异常情况
先来看一个后台返回的json
正常情况下json:
{ "code":0, "msg":"ok", "data":{ "id":5638, "newsId":5638 } }
data部分对应的实体类:
public class JsonBean { private int id; private int newsId; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getNewsId() { return newsId; } public void setNewsId(int newsId) { this.newsId = newsId; } }
异常情况json(后台数据库newsId字段未查询到对应数据):
{ "code":0, "msg":"ok", "data":{ "id":5638, "newsId":"" } }
这样Gson在解析时就会抛出解析错误的异常,app崩溃,原因是无法将""转化为int
json异常的处理
我们期望在后台返回的json异常时,也能解析成功,空值对应的转换为默认值,如:
newsId=0;
这里排除掉后台开发人员输出时给你做矫正,还是得靠自己啊---
我们写一个针对int值的类型转换器,需要实现Gson的
JsonSerializer<T>接口和
JsonDeserializer<T>,即序列化和反序列化接口
public class IntegerDefault0Adapter implements JsonSerializer<Integer>, JsonDeserializer<Integer> { @Override public Integer deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { try { if (json.getAsString().equals("") || json.getAsString().equals("null")) {//定义为int类型,如果后台返回""或者null,则返回0 return 0; } } catch (Exception ignore) { } try { return json.getAsInt(); } catch (NumberFormatException e) { throw new JsonSyntaxException(e); } } @Override public JsonElement serialize(Integer src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src); } }
同理Long及Double类型
double=>
public class DoubleDefault0Adapter implements JsonSerializer<Double>, JsonDeserializer<Double> { @Override public Double deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { try { if (json.getAsString().equals("") || json.getAsString().equals("null")) {//定义为double类型,如果后台返回""或者null,则返回0.00 return 0.00; } } catch (Exception ignore) { } try { return json.getAsDouble(); } catch (NumberFormatException e) { throw new JsonSyntaxException(e); } } @Override public JsonElement serialize(Double src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src); } }
long=>
public class LongDefault0Adapter implements JsonSerializer<Long>, JsonDeserializer<Long> { @Override public Long deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { try { if (json.getAsString().equals("") || json.getAsString().equals("null")) {//定义为long类型,如果后台返回""或者null,则返回0 return 0l; } } catch (Exception ignore) { } try { return json.getAsLong(); } catch (NumberFormatException e) { throw new JsonSyntaxException(e); } } @Override public JsonElement serialize(Long src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src); } }
所以使用是这样的:
return new Retrofit.Builder() .client(okHttpClient)//设置网络访问框架 .addConverterFactory(GsonConverterFactory.create(buildGson()))//添加json转换框架 .addCallAdapterFactory(RxJavaCallAdapterFactory.create())//让Retrofit支持RxJava .baseUrl(baseUrl) .build(); /** * 增加后台返回""和"null"的处理 * 1.int=>0 * 2.double=>0.00 * 3.long=>0L * * @return */ public static Gson buildGson() { if (gson == null) { gson = new GsonBuilder() .registerTypeAdapter(Integer.class, new IntegerDefault0Adapter()) .registerTypeAdapter(int.class, new IntegerDefault0Adapter()) .registerTypeAdapter(Double.class, new DoubleDefault0Adapter()) .registerTypeAdapter(double.class, new DoubleDefault0Adapter()) .registerTypeAdapter(Long.class, new LongDefault0Adapter()) .registerTypeAdapter(long.class, new LongDefault0Adapter()) .create(); } return gson; }
再也不会因为后台json字段为空的情况崩溃了
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能有所帮助,如果有疑问大家可以留言交流。
您可能感兴趣的文章:
相关文章推荐
- SQL2000 企业版 出现“进程51发生了严重的异常”错误的处理方法
- Eclipse检出项目,运行项目时发生异常及处理方法
- 代码阅读总结之Fitch and Mather 7.0(asp.net发生异常或错误时错误提示页面的处理方法)
- Gson解析空字符串发生异常的处理方法
- 关于jQuery load()方法加载页面后台发生异常而前台页面加载失败且没有任何展示信息的问题处理
- 运行dxp.exe运行时,软件出现:应用程序发生异常 未知的软件异常 (0x0eedfade),位置为 0x7c812afb的处理方法
- SQLserver2000 企业版 出现"进程51发生了严重的异常"错误的处理方法
- SQLserver2000 企业版 出现"进程51发生了严重的异常"错误的处理方法
- IEXPLORE.EXE[...]发生未处理的WIN32异常解决方法分享
- 关于IE7打开任何网页弹出[未处理的异常('对象不支持此属性或方法')发生在iexplorer.exe]错误调试框的解决办法
- 运行dxp.exe运行时,软件出现:应用程序发生异常 未知的软件异常 (0x0eedfade),位置为 0x7c812afb的处理方法
- c++中使用基类指针Vector 存放子类对象(0xcccccccc 处未处理的异常: 0xC0000005: 读取位置 0xcccccccc 时发生访问冲突 )
- 关于vfp调用连接服务器(linkServer)异常的处理方法
- C# MVC 处理您的请求时发生异常。此外,对第一个异常执行自定义错误页时发生另一异常。已终止请求。
- ASP 上传文件时,发生了未处理的异常 007 asp 0104不允许操作
- jquery delegate() 方法为指定的元素(属于被选元素的子元素)添加一个或多个事件处理程序,并规定当这些事件发生时运行的函数
- asp.net捕获全局未处理异常的几种方法
- struts2中处理自定义异常的方法小结
- php中异常处理方法小结
- “System.AccessViolationException”类型的未经处理的异常在 System.Drawing.dll 中发生,尝试读取或写入受保护的内存。这通常指示其他内存已损坏