java - @SerializedName 不反映在子类中
问题描述
import com.google.gson.annotations.SerializedName
class Parent {
@SerializedName("home_town")
private String homeTown;
// getters & setters
}
class Child extends Parent {
}
当我们检查/打印/记录子对象时,它具有以下内容:
{"homeTown":"blahblah"}
而我们的期望是:
{"home_town":"blahblah"}
现在如果我们在 Child 类中重写 Parent 类的 getter 方法并使用注解@JsonProperty("home_town")
,那么它就可以工作了
import com.fasterxml.jackson.annotation.JsonProperty
class Child extends Parent {
@Override
@JsonProperty("home_town")
public String getHomeTown(){
return super.getHomeTown();
}
}
我一直期待@SerializedName
应该首先通过继承与 Child 类一起工作,我有点困惑为什么它只能通过覆盖 getter 方法和注释来工作@JsonProperty
感谢你的帮助!
解决方案
我已经通过在父类中的所有 getter 上使用 @JsonProperty 来解决它,如下所示:
class Parent {
@SerializedName("home_town")
private String homeTown;
// getters & setters
@JsonProperty("home_town")
public String getHomeTown(){
return homeTown;
}
}
class Child extends Parent {
}
这就是我实现目标的方式,这样我就不需要接触 Child 类。
推荐阅读
- oracle - PLSQL(查找素数到 1000 的范围)
- kendo-ui - 剑道我如何检查标记根节点
- r - 使用多个 id 和 value 列从 long 转换为宽格式
- ios - CLLocationManager - 返回错误的速度
- vuejs2 - VueJs + Element UI:如何自定义 el-dialog 标题?
- java - 异步 JAX-RS
- c# - Async TcpClient Connect 在 Windows 和 Linux 上部署时不同
- javascript - 比较两个数组时如何更改数组中的值
- angular5 - 无法从 Angular 6 降级到 Angular 5
- html - 使用@page css 在每个页面上添加边距