源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Gson解析空字符串发生异常的处理方法

  • 时间:2020-04-17 20:49 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Gson解析空字符串发生异常的处理方法
[b]前言[/b] 在实际开发项目中,服务器经常会用空字符串 “” 作为返回结果表示空值 ,但这在Gson当中就会遇到问题,如果这项数据的类型不是字符串,Gson解析就会报错 [b]Json异常情况[/b] 先来看一个后台返回的json [b]正常情况下json:[/b]
{
 "code":0,
 "msg":"ok",
 "data":{
  "id":5638,
  "newsId":5638
 }
}
[b]data部分对应的实体类:[/b]
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;
 }
}
[b]异常情况json[/b](后台数据库newsId字段未查询到对应数据):
{
 "code":0,
 "msg":"ok",
 "data":{
  "id":5638,
  "newsId":""
 }
}
这样Gson在解析时就会抛出解析错误的异常,app崩溃,原因是无法将""转化为int [b]json异常的处理[/b] 我们期望在后台返回的json异常时,也能解析成功,空值对应的转换为默认值,如:[code]newsId=0;[/code] 这里排除掉后台开发人员输出时给你做矫正,还是得靠自己啊--- 我们写一个针对int值的类型转换器,需要实现Gson的[code] JsonSerializer<T>[/code] 接口和 [code]JsonDeserializer<T>[/code] ,即序列化和反序列化接口
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);
 }
}
[b]同理Long及Double类型[/b] [b]double=>[/b]
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);
 }
}
[b]long=>[/b]
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);
 }
}
[b]所以使用是这样的:[/b]
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字段为空的情况崩溃了 [b]总结[/b] 以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能有所帮助,如果有疑问大家可以留言交流。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部