Reputation: 644
I am getting a json from a server (not my server) that contains the key 'id'. I want to deserialize it into a variable called 'jsonId' inside my object. I used @SerializedName("id") to do it, but the problem is that my object also has variable called id, and because of that i get duplication error.
How can I map 'id' to the variable 'jsonId', while igonring the 'id' variable?
Thanks.
Upvotes: 3
Views: 691
Reputation: 280054
I can think of two options.
One option is to mark your field named id
as transient
. Gson ignores any field modified with transient
.
If a field is marked transient, (by default) it is ignored and not included in the JSON serialization or deserialization.
Another option is to annotate the jsonId
field (and all other relevant fields) with @Expose
and build your Gson
instance to exclude fields without the annotation. For example,
Gson mapper = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
Gson will now only deserialize those fields that are annotated with @Expose
. It will not consider any others.
Upvotes: 2