parvesh-garg-zettata / google-gson

Automatically exported from code.google.com/p/google-gson
0 stars 0 forks source link

Disable @SerializedName usage via GsonBuilder #633

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
Reading json is fairy easy when field name are self-explainatory.
However, in some case we choose to trade this readability for smaller files by 
providing a shorter serialization name for a field (via @SerializedName).

Typically this is the case for development (readability) and production 
(smaller file size) environments.

Therefor I would like to disable the @SerializedName usage (default would be 
enabled) via the GsonBuilder.

At the moment I saw that the setFieldNamingStrategy() method can be used to 
control the json naming but it is only applied when no @SerializedName 
annotation is present.

One solution I see would be not to use the @SerializedName and create my own 
NamingStrategy and Annotation (ex: MySerializedName) as follows :

public enum FieldNamingPolicy implements FieldNamingStrategy {

    /** Use the field full name */
    DEV() {
        public String translateName(Field f) {
            return f.getName();
        }
    },

    /** Use the SerializedName annotation, if available */
    PROD() {
        public String translateName(Field f) {
            if (f.isAnnotationPresent(MySerializedName.class)) {
                return f.getAnnotation(MySerializedName.class).value();
            }
            return f.getName();
        }
    }
}

But I find this solution worse than having it directly in Gson.
The main reason would be that the support for Enum would be lost (since it rely 
on @SerializedName).

Please find here under a simple TestCase for this request :

    class Obj {

        public String normalField;

        @SerializedName("long")
        public String veryLongDescriptiveFieldName;

        public Obj(String a, String b) {
            this.normalField = a;
            this.veryLongDescriptiveFieldName = b;
        }

    }

    @Test
    public void Prod() {
        Gson gson = new GsonBuilder().create();
        Assert.assertEquals("{\"normalField\":\"a\",\"long\":\"b\"}", gson.toJson(new Obj("a", "b")));
    }

    @Test
    public void Dev() {
        Gson gson = new GsonBuilder().disableSerializedNameAnnotation().create();
        Assert.assertEquals("{\"normalField\":\"a\",\"veryLongDescriptiveFieldName\":\"b\"}", gson.toJson(new Obj("a", "b")));
    }

Original issue reported on code.google.com by o...@informex.be on 27 Mar 2015 at 2:02