首页 > 解决方案 > @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

感谢你的帮助!

标签: javagsonfasterxml

解决方案


我已经通过在父类中的所有 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 类。


推荐阅读