import com.google.gson.annotations.SerializedName
class Parent {
@SerializedName("home_town")
private String homeTown;
// getters & setters
}
class Child extends Parent {
}
when we check/print/log the child object it has something like:
{"homeTown":"blahblah"}
whereas our expectation is:
{"home_town":"blahblah"}
Now if we override the getter method of Parent class in Child class and annotate using @JsonProperty("home_town")
, then it works
import com.fasterxml.jackson.annotation.JsonProperty
class Child extends Parent {
@Override
@JsonProperty("home_town")
public String getHomeTown(){
return super.getHomeTown();
}
}
I had been expecting @SerializedName
should have worked with Child class too in the first place through inheritance, I am little puzzled that why it worked only by overriding the getter method and annotating with @JsonProperty
Appreciate your help!
I've resolved it by using @JsonProperty on all getters in parent class like follows:
class Parent {
@SerializedName("home_town")
private String homeTown;
// getters & setters
@JsonProperty("home_town")
public String getHomeTown(){
return homeTown;
}
}
class Child extends Parent {
}
This is how I've achieved my objective, this way I do not need to touch the Child class.