面對一些不規範的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; }