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

Android:Gson处理int字段空值失败,指定字段序列化null无效求助

解决Gson反序列化空字符串到数值字段的崩溃问题

看起来你搞混了序列化和反序列化的概念哦——serializeNulls()是用来控制Gson把Java对象转成JSON时,是否输出值为null的字段,而你现在遇到的是反过来:JSON里的id是空字符串"",但你的POJO里是Integer/int类型,Gson默认没法把空字符串转成数值类型,所以才抛出NumberFormatException。

问题根源

你的JSON有两种格式:

  • 格式1:"character": { "id": "", "name": "" } —— id是空字符串
  • 格式2:"character": { "id": 10, "name": "İrem" } —— id是正常数值

Gson默认的数值类型适配器会尝试把字符串转成Integer/int,但空字符串无法解析,直接抛出异常。

解决方案:自定义TypeAdapter处理空字符串

我们可以写一个自定义的TypeAdapter,让Gson在遇到空字符串时自动转成null(或者你需要的默认值,比如0),同时兼容正常的数值解析。

1. 编写自定义Integer类型适配器

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;

public class IntegerTypeAdapter extends TypeAdapter<Integer> {
    @Override
    public void write(JsonWriter out, Integer value) throws IOException {
        // 序列化时处理null(如果需要的话)
        if (value == null) {
            out.nullValue();
            return;
        }
        out.value(value);
    }

    @Override
    public Integer read(JsonReader in) throws IOException {
        // 处理JSON里的null或空字符串
        if (in.peek() == JsonToken.NULL) {
            in.nextNull();
            return null;
        }
        String rawValue = in.nextString();
        if (rawValue.trim().isEmpty()) {
            return null; // 这里可以改成return 0,根据你的业务需求选择
        }
        // 正常解析数值
        try {
            return Integer.parseInt(rawValue);
        } catch (NumberFormatException e) {
            // 如果遇到非数值的字符串,也可以返回null或者抛出自定义异常
            return null;
        }
    }
}

2. 注册适配器到Gson

创建Gson实例时,把这个适配器注册进去,这样所有Integer/int类型的字段都会用这个规则解析:

Gson gson = new GsonBuilder()
        .registerTypeAdapter(Integer.class, new IntegerTypeAdapter())
        .registerTypeAdapter(int.class, new IntegerTypeAdapter()) // 如果你用int基本类型的话
        .create();

3. 或者直接用注解绑定到字段

如果你只想让某个特定字段用这个适配器,可以在POJO的字段上加上@JsonAdapter注解,不用全局注册:

import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;

public class Character {
    @SerializedName("name")
    private String name;

    @SerializedName("id")
    @JsonAdapter(IntegerTypeAdapter.class)
    private Integer id;

    // getter和setter省略
}

针对基本类型int的注意点

如果你的POJO里id是int(基本类型),那不能返回null,因为基本类型没有null值。这时候要把适配器里的return null改成return 0(或者其他你需要的默认数值),否则会抛出NullPointerException。

为什么serializeNulls()没用?

再强调一次:serializeNulls()是序列化场景的配置——比如你的Java对象里id是null,用这个配置后,Gson会把它序列化成"id": null,而不是忽略这个字段。但你现在是反序列化JSON到Java对象,所以这个配置完全不生效哦。

内容的提问来源于stack exchange,提问作者Hasan Kucuk

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:19:56