Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configure Gson to change key in json

Tags:

java

json

gson

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"}
like image 969
Gaurav Gupta Avatar asked Jan 10 '23 23:01

Gaurav Gupta


1 Answers

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"))

like image 58
fge Avatar answered Jan 17 '23 21:01

fge