Gson解析空字符串异常的处理

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


11月9日更新:
关于数组类型的字段解析异常,我尝试了一些方案,但最后都存在问题,如果大家有好的解决方案,希望能贴在下面.不甚感激.
异常示例=>正常json:

{
    "code":0,
    "msg":"ok",
    "data":[    //约定为数组
      {
        "id":5638,
        "newsId":5638
      }
      ]
}

异常json:

{
    "code":0,
    "msg":"ok",
    "data":{}    //返回为对象或者空字符串
}

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字段为空的情况崩溃了

关于作者

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 1.概述2.Gson的目标3.Gson的性能和扩展性4.Gson的使用者5.如何使用Gson 通过Maven来使用...
    人失格阅读 14,867评论 2 18
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,270评论 19 139
  • 点击查看原文 Web SDK 开发手册 SDK 概述 网易云信 SDK 为 Web 应用提供一个完善的 IM 系统...
    layjoy阅读 14,778评论 0 15
  • 这个文章比较“肤浅”,但是其实网上对于Fragment切换这么肤浅的事情也甚少有文章说的清楚,所以稍微介绍下。 B...
    聪葱忙忘阅读 12,939评论 13 8
  • 徐云霞说道 :“既然胡大哥有祖训在身小弟也不便勉强,只是小弟仍有一事相求,还望胡大哥应允。” 胡斐说道 :“虽然胡...
    长白居士阅读 1,868评论 0 0

友情链接更多精彩内容