面对一些不规范的json,我们的gson解析经常会抛出各种异常导致app崩溃,这里可以采取一些措施来避免。

我们期望在后台返回的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 ;
}
} 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类型

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 ;
}
} 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);
}
}

同理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);
}
}

使用方法

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;
}

Gson解析空字符串异常的处理的更多相关文章

  1. 【Android进阶】Gson解析json字符串的简单应用

    在客户端与服务器之间进行数据传输,一般采用两种数据格式,一种是xml,一种是json.这两种数据交换形式各有千秋,比如使用json数据格式,数据量会比较小,传输速度快,放便解析,而采用xml数据格式, ...

  2. Gson解析json字符串、json数组转换成对象

    实体类: public class Product { private int id; private String name; private String date; public int get ...

  3. Android用Gson解析JSON字符串

    在volley框架中有一个 protected Response<Result<T>> parseNetworkResponse(NetworkResponse respons ...

  4. Gson解析json字符串

    // 解析传递过来的json字符串 JsonParser parser = new JsonParser(); JsonObject jsonObj = parser.parse(strJson).g ...

  5. 用Gson解析没有数据头的纯数组json字符串

    无数据头Json字符串 Json字符串只有数组,而次数组没有名字,如下 [ { "name": "zhangsan", "age": &qu ...

  6. Android解析Json数据之Gson解析

    Gson是谷歌官方提供的解析json数据的工具类.json数据的解析能够使用JSONObject和JSONArray配合使用解析数据,可是这样的原始的方法对于小数据的解析还是有作用的,可是陪到了复杂数 ...

  7. 在线聊天项目1.4版 使用Gson方法解析Json字符串以便重构request和response的各种请求和响应 解决聊天不畅问题 Gson包下载地址

    在线聊天项目结构图: 多用户登陆效果图: 多用户聊天效果图: 数据库效果图: 重新构建了Server类,使用了Gson方法,通过解析Json字符串,增加Info类,简化判断过程. Server类代码如 ...

  8. Gson 解析教程

    Gson 是google解析Json的一个开源框架,同类的框架fastJson,JackJson等等 本人fastJson用了两年,也是从去年才开始接触Gson,希望下面的总结会对博友有用,至于Gso ...

  9. Gson解析List的一点小问题

    这阵子在使用gson解析时遇到了点小麻烦,因为一直用的fastjson,最近一个项目里使用的gson,需要解析list集合,查资料都是使用TypeToken解决,相对比较麻烦,下面为大伙推荐一种简便的 ...

随机推荐

  1. spring boot -thymeleaf-异常处理

    异常流程 :controller-ControllerAdvice-异常解析器-默认的error页面 1.错误页面error.html: 程序出现异常会自动跳到error.html里,视频效果,该页面 ...

  2. ASCII码字符串普通加密解密-android

    //android后台Java //ASCII加密 String str = e.getText().toString(); StringBuilder s = new StringBuilder() ...

  3. ASP .NET CORE 根据环境变量支持多个 appsettings.json

    0.背景 在开发项目的过程当中,生产环境与调试环境的配置肯定是不一样的.拿个最简单的例子来说,比如连接字符串这种东西,调试环境肯定是不能连接生产数据库的.在之前的话,这种情况只能说是你 COPY 两个 ...

  4. odoo开发笔记 -- 模型字段定义中设置默认值

    例如: company_id = fields.Many2one('res.company', string='Company', default=lambda self: self.env['res ...

  5. 浅尝Spring Cloud Sleuth

    Spring Cloud Sleuth提供了分布式追踪(distributed tracing)的一个解决方案.其基本思路是在服务调用的请求和响应中加入ID,标明上下游请求的关系.利用这些信息,可以方 ...

  6. Linux编程 24 shell编程(结构化 if [ condition ] 数值比较,字符串比较)

    一.概述 接着上篇讲的结构化命令,最后讲到了test命令的另一种写法 if [ condition ],它的语法格式如下: --格式如下: if [ condition ] then commands ...

  7. Java 容器 & 泛型:二、ArrayList 、LinkedList和Vector比较

    Writer:BYSocket(泥沙砖瓦浆木匠) 微博:BYSocket 豆瓣:BYSocket 继续上一篇的容器文章认识容器,泥瓦匠慢慢带你们走进List的容器解说.今天泥瓦匠想说说 ArrayLi ...

  8. Core2.0知识整理

    概述 Commond-Line ASP.NET结构文件 Startup 配置文件 中间件和依赖注入 依赖注入原理 框架自带的依赖注入(IServiceCollection) 依赖注入生命周期 依赖注入 ...

  9. PEB标记反调试方法

    PEB标记反调试方法 一丶PEB结构简介 PEB.简称进程环境快. 我们在讲DLL隐藏的时候已经说过了. 具体博客链接: https://www.cnblogs.com/iBinary/p/96018 ...

  10. 解决Linux下Jexus验证码无法显示

    1:安装mono相关字体 yum install -y dejavu-fonts-common dejavu-lgc-sans-mono-fonts 2:重启jexus /usr/jexus/jws ...