标题:
gson 序列化model 闪退
错误信息:
java.lang.NumberFormatException: empty String
错误原因:
类型不统一,gson 后台 string 转 int时,“” 导致崩溃
eg:
{
"name" : "Test1",
"business_type" : "90"
}
{
"name" : "Test1",
"business_type" : ""
}
@SerializedName("business_type")
int businessType;
解决方案:
Gson gson = new Gson();
替换为
private Gson gson = new GsonBuilder()
.registerTypeAdapter(int.class, new IntTypeAdapter())
.registerTypeAdapter(Integer.class, new IntTypeAdapter()).create();
工具类如下
class IntTypeAdapter extends TypeAdapter<Number> {
@Override
public void write(JsonWriter out, Number value)
throws IOException {
out.value(value);
}
@Override
public Number read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) {
in.nextNull();
return null;
}
try {
String result = in.nextString();
if ("".equals(result)) {
return null;
}
return Integer.parseInt(result);
} catch (NumberFormatException e) {
throw new JsonSyntaxException(e);
}
}
}
网友评论