You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 01:15:51