Java类@SerializedName注解映射JSON失败,如何解决?
解决方案
核心原因
@SerializedName是GSON库专属的序列化注解,Jackson默认不识别它,因此会按照字段名engineId去JSON中匹配键名,自然找不到engine_id导致报错。
方案1:改用Jackson原生注解
将@SerializedName替换为Jackson自带的@JsonProperty注解,直接指定JSON对应的键名:
import com.fasterxml.jackson.annotation.JsonProperty; public class CustomClass { public static final String SERIALIZED_NAME_ENGINE_ID = "engine_id"; @JsonProperty(SERIALIZED_NAME_ENGINE_ID) private String engineId; // 需添加getter/setter,Jackson依赖它们访问字段 public String getEngineId() { return engineId; } public void setEngineId(String engineId) { this.engineId = engineId; } }
保持原有Jackson解析代码不变,即可正常映射{"engine_id": "Test"}到CustomClass实例。
方案2:让Jackson兼容GSON的@SerializedName
若不想修改现有注解,可引入Jackson的GSON兼容模块:
- 添加Maven依赖(版本需与你的Jackson版本一致):
<dependency> <groupId>com.fasterxml.jackson.module</groupId> <artifactId>jackson-module-gson</artifactId> <version>你的Jackson版本号</version> </dependency>
- 配置
ObjectMapper启用该模块:
String json = "{\"engine_id\": \"Test\"}"; ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new GsonModule()); CustomClass sample = mapper.readValue(json, CustomClass.class);
配置后Jackson就能识别@SerializedName注解。
方案3:直接用GSON解析(推荐)
既然代码已使用GSON的@SerializedName,直接用GSON解析最省心:
- 添加GSON依赖:
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>最新稳定版</version> </dependency>
- 解析代码:
import com.google.gson.Gson; String json = "{\"engine_id\": \"Test\"}"; Gson gson = new Gson(); CustomClass sample = gson.fromJson(json, CustomClass.class);
无需修改现有类的注解,GSON会自动根据@SerializedName("engine_id")完成JSON键与字段的映射。
内容的提问来源于stack exchange,提问作者ankit patil
相关产品推荐
相关产品推荐

