I am thinking of using Gson in my web-service, but i observed that Gson returns name of a variable in class as a key in Json format
.
E.g
interface Animal{
}
class Dog implements Animal{
public String name, age;
@Override
public String toString() {
return name+"\t" + age;
}
}
Json for object of Dog is as follows:
{"name":"Tommy","age":"12"}
Now, my problem is since Key(name
and age
) in Json are dependent on name of variable, So if my variable name changes then key also changes. Then client for this web-service has to change the code whenever a variable name changes in web-service.
So Is their any way, so that i can map every variable with a key name. For e.g mapping name to nameOfDog
and age to ageOfDog
, so that json will look like
{"nameOfDog":"Tommy","ageOfDog":"12"}
Yes, using the SerializedName
annotation.
Since is has a @Target(value=FIELD)
, it can (only) be applied to instance fields.
So:
@SerializedName("nameOfDog")
String name;
(in Jackson that would be @JsonProperty("nameOfDog")
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With