Preface
In actual development projects, the server often uses the empty string "" as the return result to represent the empty value, but this will encounter problems in Gson. If the type of this data is not a string, Gson will report an error when parsing it.
Json exception
Let's first look at a json returned in the background
Under normal circumstances json:
{ "code":0, "msg":"ok", "data":{ "id":5638, "newsId":5638 } }
The entity class corresponding to the data part:
public class JsonBean { private int id; private int newsId; public int getId() { return id; } public void setId(int id) { = id; } public int getNewsId() { return newsId; } public void setNewsId(int newsId) { = newsId; } }
Exception json(The corresponding data was not queried in the newsId field of the background database):
{ "code":0, "msg":"ok", "data":{ "id":5638, "newsId":"" } }
In this way, Gson will throw an exception with parsing errors when parsing, and the app crashes because it cannot convert "" into int
Handling of json exceptions
We expect that when the json exception returned in the background can be successfully parsed, the corresponding null value is converted to the default value, such as:newsId=0;
Here we exclude the corrections for you when the background developers outputs, but we still have to rely on ourselves--
We write a type converter for int values, which needs to implement Gson's JsonSerializer<T>
Interface andJsonDeserializer<T>
, i.e. serialization and deserialization interfaces
public class IntegerDefault0Adapter implements JsonSerializer<Integer>, JsonDeserializer<Integer> { @Override public Integer deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { try { if (().equals("") || ().equals("null")) {//Define as int type, if the background returns "" or null, it returns 0 return 0; } } catch (Exception ignore) { } try { return (); } catch (NumberFormatException e) { throw new JsonSyntaxException(e); } } @Override public JsonElement serialize(Integer src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src); } }
Similarly, Long and Double types
double=>
public class DoubleDefault0Adapter implements JsonSerializer<Double>, JsonDeserializer<Double> { @Override public Double deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { try { if (().equals("") || ().equals("null")) {//Define as double type. If the background returns "" or null, it returns 0.00 return 0.00; } } catch (Exception ignore) { } try { return (); } 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 (().equals("") || ().equals("null")) {//Define as long type, if the background returns "" or null, return 0 return 0l; } } catch (Exception ignore) { } try { return (); } catch (NumberFormatException e) { throw new JsonSyntaxException(e); } } @Override public JsonElement serialize(Long src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src); } }
So use is like this:
return new () .client(okHttpClient)//Set up a network access framework .addConverterFactory((buildGson()))//Add json conversion framework .addCallAdapterFactory(())//Let Retrofit support RxJava .baseUrl(baseUrl) .build(); /** * Added the processing of "" and "null" in the background * =>0 * =>0.00 * => 0L * * @return */ public static Gson buildGson() { if (gson == null) { gson = new GsonBuilder() .registerTypeAdapter(, new IntegerDefault0Adapter()) .registerTypeAdapter(, new IntegerDefault0Adapter()) .registerTypeAdapter(, new DoubleDefault0Adapter()) .registerTypeAdapter(, new DoubleDefault0Adapter()) .registerTypeAdapter(, new LongDefault0Adapter()) .registerTypeAdapter(, new LongDefault0Adapter()) .create(); } return gson; }
Will never crash because the background json field is empty again
Summarize
The above is the entire content of this article. I hope the content of this article will be helpful to everyone's study or work. If you have any questions, you can leave a message to communicate.