面对一些不规范的json,咱们的gson解析常常会抛出各类异常致使app崩溃,这里能够采起一些措施来避免。json
咱们指望在后台返回的json异常时,也能解析成功,空值对应的转换为默认值,如:newsId=0;
这里排除掉后台开发人员输出时给你作矫正,仍是得靠本身啊---网络
咱们写一个针对int值的类型转换器,须要实现Gson的JsonSerializer<T>
接口和JsonDeserializer<T>
,即序列化和反序列化接口app
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); } }
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 0; } } 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); } }
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; }