如何修复RecyclerView因JsonSyntaxException引发的崩溃问题?
解决Gson解析引发的NumberFormatException崩溃问题
问题根源
报错com.google.gson.JsonSyntaxException: java.lang.NumberFormatException:Expected an int but was 0.5明确说明:你定义的实体类中,$.items[10].weight字段的类型是int,但接口返回的对应值是小数0.5,Gson无法将小数解析为整数,导致崩溃。
解决方案
修改实体类字段类型(最直接)
把实体类中weight字段的类型从int改为float或double,适配接口返回的小数格式:public class ItemModel { // 其他字段 private double weight; // 或使用float // getter、setter方法 }自定义TypeAdapter兼容类型(不修改字段类型时用)
如果业务逻辑必须让weight保持int类型,可以自定义Gson的TypeAdapter,将返回的小数转为整数(比如取整、四舍五入):public class IntWeightAdapter extends TypeAdapter<Integer> { @Override public void write(JsonWriter out, Integer value) throws IOException { out.value(value); } @Override public Integer read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NUMBER) { // 先读取为字符串,再转成double后转int,避免直接解析报错 double num = Double.parseDouble(in.nextString()); // 这里可根据需求选择取整方式:直接截断小数部分或四舍五入 return (int) num; // 直接取整 // return (int) Math.round(num); // 四舍五入 } throw new JsonSyntaxException("无法解析为整数类型"); } }然后在创建Gson实例时注册这个适配器:
Gson gson = new GsonBuilder() .registerTypeAdapter(Integer.class, new IntWeightAdapter()) .create();协调后端统一字段类型
和后端开发人员确认weight字段的预期类型,要求接口返回统一的数值类型,从根源避免类型不匹配问题。
内容的提问来源于stack exchange,提问作者Md. Fazle Rabbi
相关产品推荐
相关产品推荐

