add FieldNamingPolicy.LOWER_CASE_WITH_DOTS (#1278)

This commit is contained in:
Leon 2018-04-28 09:50:08 +08:00 committed by inder123
parent be23a3aeeb
commit ab35f11077
2 changed files with 31 additions and 0 deletions

View File

@ -114,6 +114,29 @@ public enum FieldNamingPolicy implements FieldNamingStrategy {
@Override public String translateName(Field f) { @Override public String translateName(Field f) {
return separateCamelCase(f.getName(), "-").toLowerCase(Locale.ENGLISH); return separateCamelCase(f.getName(), "-").toLowerCase(Locale.ENGLISH);
} }
},
/**
* Using this naming policy with Gson will modify the Java Field name from its camel cased
* form to a lower case field name where each word is separated by a dot (.).
*
* <p>Here's a few examples of the form "Java Field Name" ---> "JSON Field Name":</p>
* <ul>
* <li>someFieldName ---> some.field.name</li>
* <li>_someFieldName ---> _some.field.name</li>
* <li>aStringField ---> a.string.field</li>
* <li>aURL ---> a.u.r.l</li>
* </ul>
* Using dots in JavaScript is not recommended since dot is also used for a member sign in
* expressions. This requires that a field named with dots is always accessed as a quoted
* property like {@code myobject['my.field']}. Accessing it as an object field
* {@code myobject.my.field} will result in an unintended javascript expression.
* @since 2.8
*/
LOWER_CASE_WITH_DOTS() {
@Override public String translateName(Field f) {
return separateCamelCase(f.getName(), ".").toLowerCase(Locale.ENGLISH);
}
}; };
/** /**

View File

@ -63,6 +63,14 @@ public class NamingPolicyTest extends TestCase {
+ target.someConstantStringInstanceField + "\"}", gson.toJson(target)); + target.someConstantStringInstanceField + "\"}", gson.toJson(target));
} }
public void testGsonWithLowerCaseDotPolicySerialization() {
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DOTS).create();
StringWrapper target = new StringWrapper("blah");
assertEquals("{\"some.constant.string.instance.field\":\""
+ target.someConstantStringInstanceField + "\"}", gson.toJson(target));
}
public void testGsonWithLowerCaseDashPolicyDeserialiation() { public void testGsonWithLowerCaseDashPolicyDeserialiation() {
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES).create(); Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES).create();
String target = "{\"some-constant-string-instance-field\":\"someValue\"}"; String target = "{\"some-constant-string-instance-field\":\"someValue\"}";