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

Retrofit如何处理接口请求时出现的NumberFormatException异常?

解决Retrofit+Gson解析空字符串到int字段的异常问题

这个坑我之前踩过!你遇到的com.google.gson.JsonSyntaxException本质是Gson默认解析规则没法把空字符串""转换成int类型——毕竟空字符串不是合法的数字格式。给你几个实用的解决思路:

1. 全局注册Gson类型适配器(推荐)

写一个自定义的类型适配器,让Gson遇到空字符串或者非数字格式的内容时,自动转换成默认值(比如0),这样所有int/Integer字段都能通用:

首先创建适配器类:

public class IntTypeAdapter 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.NULL) {
            in.nextNull();
            return 0; // 空值时返回0,也可以返回null(如果用Integer类型的话)
        }
        String strValue = in.nextString().trim();
        try {
            return Integer.parseInt(strValue);
        } catch (NumberFormatException e) {
            // 遇到空字符串或非数字时返回默认值
            return 0;
        }
    }
}

然后在构建Retrofit的时候,把这个适配器注册到Gson中:

Gson customGson = new GsonBuilder()
        .registerTypeAdapter(Integer.class, new IntTypeAdapter())
        .registerTypeAdapter(int.class, new IntTypeAdapter())
        .create();

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(YOUR_BASE_URL)
        .addConverterFactory(GsonConverterFactory.create(customGson))
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .build();

2. 单独给字段加注解

如果只有count这一个字段有问题,不想全局修改,可以直接在实体类的字段上用@JsonAdapter注解指定适配器:

class QueryResult {
    @JsonAdapter(IntTypeAdapter.class)
    int count;
    // ...其他字段
}

3. 从根源解决:让后端修正返回值

如果能联系到后端开发,最好让他们把空字符串""改成合法的数字格式,比如0或者null,这是最彻底的方案,避免后续其他字段出现类似问题。

补充说明

Gson默认的解析逻辑是:当遇到int类型字段时,会尝试把JSON里的对应值直接转成整数,但如果JSON里是""这种空字符串,就会触发NumberFormatException,最终包装成JsonSyntaxException抛出来。我们自定义的适配器就是在解析环节拦截了这种情况,做了兼容处理。

内容的提问来源于stack exchange,提问作者Pai-Hsiang Huang

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:25:08