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

Java GSON反序列化异常:同类型字段playerName解析为null

解决GSON反序列化时playerName字段为null的问题

可能的原因及对应解决方案

1. 构造器参数不匹配

GSON默认通过反射匹配构造器参数,如果SentPlayer的构造器参数顺序、名称和类字段不对应,会导致playerName赋值失败。比如构造器参数顺序是uuid, universeUuid, playerName,或者参数名用了name而非playerName。

解决方法:
确保构造器参数和字段完全对应,或者给构造器参数加@SerializedName注解绑定JSON字段名:

public class SentPlayer {
    final String uuid;
    final String playerName;
    final String universeUuid;

    public SentPlayer(@SerializedName("uuid") String uuid,
                      @SerializedName("playerName") String playerName,
                      @SerializedName("universeUuid") String universeUuid) {
        this.uuid = uuid;
        this.playerName = playerName;
        this.universeUuid = universeUuid;
    }

    // 对应的get方法
}

2. 字段访问权限问题

GSON需要能访问到字段完成赋值,如果SentPlayer的playerName是私有字段,且没有配置GSON允许访问私有成员,会导致赋值失败。

解决方法:
要么将SentPlayer的字段改为public,要么在构建GSON时开启私有字段访问支持:

Gson gson = new GsonBuilder()
        .serializeNulls()
        .setFieldNamingPolicy(FieldNamingPolicy.IDENTITY)
        .create();

也可以给字段添加@Expose注解,同时配置GSON启用该注解:

public class SentPlayer {
    @Expose
    final String uuid;
    @Expose
    final String playerName;
    @Expose
    final String universeUuid;

    // 构造器及get方法
}

// 构建GSON实例
Gson gson = new GsonBuilder()
        .serializeNulls()
        .excludeFieldsWithoutExposeAnnotation()
        .create();

3. 字段命名策略不匹配

如果GSON使用了非IDENTITY的命名策略(比如驼峰转下划线),会导致playerName无法匹配JSON中的同名键。

解决方法:
显式设置命名策略为IDENTITY,确保字段名和JSON键完全一致:

Gson gson = new GsonBuilder()
        .serializeNulls()
        .setFieldNamingPolicy(FieldNamingPolicy.IDENTITY)
        .create();

4. 类缓存或编译问题

如果项目存在构建缓存,或者运行的是旧版本的SentPlayer类文件,可能导致字段映射异常。

解决方法:

  • 清理项目构建缓存(比如Maven执行clean,Gradle执行cleanBuildCache)
  • 重新编译项目,确保运行的是最新版本的类文件

5. JSON数据隐形问题

检查API返回的JSON中playerName键是否存在隐形字符(如空格、不可见Unicode字符),导致GSON无法匹配字段名。

解决方法:
用文本编辑器打开JSON内容排查隐形字符,或者要求API修复返回的JSON数据,确保playerName键名无额外字符。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 09:12:46