zeroboo
zeroboo

Reputation: 8965

Gson: how to ignore @SerializeName when serializing

I have a class like this

public class Person()
{
    @SerializedName("c")
    public String name;
    @SerializedName("i")
    public int id;
}

Can i serialize it in manner of retain the field name, not the serialize name without removing the annotation?

I can't change class declaration cause these annotation are used for serializing to database, and i want to make a readable string of these objects for debugging.

eg: {"name":"Mark","id":0} instead of {"c":"Mark","i":0}

Upvotes: 1

Views: 2257

Answers (2)

pwb
pwb

Reputation: 115

You may try to use alternate in annotation. @SerializedName(value = "c", alternate = "name")

Upvotes: 0

Oleg Gryb
Oleg Gryb

Reputation: 5249

Just remove @SerializedName("c"). By default it should be 'name' after serialization.

See explanation and example here: http://google-gson.googlecode.com/svn/tags/1.2.3/docs/javadocs/com/google/gson/annotations/SerializedName.html

That seems to be exactly your case.

If the data file should not be edited, as the author has suggested in the question update, an alternative solution can be changing or deleting @SerializedName("c") annotation through Java reflection, which is described in details here: http://google-gson.googlecode.com/svn/tags/1.2.3/docs/javadocs/com/google/gson/annotations/SerializedName.html

Upvotes: 4

Related Questions