Status: New
Owner: ----
Labels: Type-Defect Priority-Medium
New issue 633 by
o...@informex.be: Disable @SerializedName usage via
GsonBuilder
https://code.google.com/p/google-gson/issues/detail?id=633
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")));
}
--
You received this message because this project is configured to send all
issue notifications to this address.
You may adjust your notification preferences at:
https://code.google.com/hosting/settings