Tighten up some of the fields naming policy code. The main thrust of this change is replacing classes like UpperCaseNamingPolicy with the corresponding method calls. Classes like CompositeFieldNamingPolicy are replaced by sequences of method calls. This also replaces unit tests with functional tests.

One nice benefit of this is a 3%/5.7KiB reduction in the size of gson.jar to 184KiB.
This commit is contained in:
Jesse Wilson 2011-11-21 05:08:23 +00:00
parent f777a192ee
commit f89e92aa9f
26 changed files with 176 additions and 1212 deletions

View File

@ -1,75 +0,0 @@
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson;
import com.google.gson.internal.$Gson$Preconditions;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Collection;
/**
* Converts the field name that uses camel-case define word separation into separate words that
* are separated by the provided {@code separatorString}.
*
* <p>The following is an example:</p>
* <pre>
* class IntWrapper {
* public int integerField = 0;
* }
*
* CamelCaseSeparatorNamingPolicy policy = new CamelCaseSeparatorNamingPolicy("_");
* String translatedFieldName =
* policy.translateName(IntWrapper.class.getField("integerField"));
*
* assert("integer_Field".equals(translatedFieldName));
* </pre>
*
* @author Joel Leitch
*/
final class CamelCaseSeparatorNamingPolicy extends RecursiveFieldNamingPolicy {
private final String separatorString;
/**
* Constructs a new CamelCaseSeparatorNamingPolicy object that will add the
* {@code separatorString} between each of the words separated by camel case.
*
* @param separatorString the string value to place between words
* @throws IllegalArgumentException thrown if the {@code separatorString} parameter
* is null or empty.
*/
public CamelCaseSeparatorNamingPolicy(String separatorString) {
$Gson$Preconditions.checkNotNull(separatorString);
$Gson$Preconditions.checkArgument(!"".equals(separatorString));
this.separatorString = separatorString;
}
@Override
protected String translateName(String target, Type fieldType,
Collection<Annotation> annnotations) {
StringBuilder translation = new StringBuilder();
for (int i = 0; i < target.length(); i++) {
char character = target.charAt(i);
if (Character.isUpperCase(character) && translation.length() != 0) {
translation.append(separatorString);
}
translation.append(character);
}
return translation.toString();
}
}

View File

@ -1,46 +0,0 @@
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Collection;
/**
* Performs numerous field naming translations wrapped up as one object.
*
* @author Joel Leitch
*/
abstract class CompositionFieldNamingPolicy extends RecursiveFieldNamingPolicy {
private final RecursiveFieldNamingPolicy[] fieldPolicies;
public CompositionFieldNamingPolicy(RecursiveFieldNamingPolicy... fieldNamingPolicies) {
if (fieldNamingPolicies == null) {
throw new NullPointerException("naming policies can not be null.");
}
this.fieldPolicies = fieldNamingPolicies;
}
@Override
protected String translateName(String target, Type fieldType, Collection<Annotation> annotations) {
for (RecursiveFieldNamingPolicy policy : fieldPolicies) {
target = policy.translateName(target, fieldType, annotations);
}
return target;
}
}

View File

@ -16,6 +16,8 @@
package com.google.gson;
import java.lang.reflect.Field;
/**
* An enumeration that defines a few standard naming conventions for JSON field names.
* This enumeration should be used in conjunction with {@link com.google.gson.GsonBuilder}
@ -25,7 +27,18 @@ package com.google.gson;
* @author Inderjeet Singh
* @author Joel Leitch
*/
public enum FieldNamingPolicy {
public enum FieldNamingPolicy implements FieldNamingStrategy {
/**
* Using this naming policy with Gson will ensure that the field name is
* unchanged.
*/
IDENTITY() {
public String translateName(Field f) {
return f.getName();
}
},
/**
* Using this naming policy with Gson will ensure that the first "letter" of the Java
* field name is capitalized when serialized to its JSON form.
@ -36,8 +49,11 @@ public enum FieldNamingPolicy {
* <li>_someFieldName ---> _SomeFieldName</li>
* </ul>
*/
UPPER_CAMEL_CASE(new ModifyFirstLetterNamingPolicy(
ModifyFirstLetterNamingPolicy.LetterModifier.UPPER)),
UPPER_CAMEL_CASE() {
public String translateName(Field f) {
return upperCaseFirstLetter(f.getName());
}
},
/**
* Using this naming policy with Gson will ensure that the first "letter" of the Java
@ -49,11 +65,15 @@ public enum FieldNamingPolicy {
* <li>someFieldName ---> Some Field Name</li>
* <li>_someFieldName ---> _Some Field Name</li>
* </ul>
*
*
* @since 1.4
*/
UPPER_CAMEL_CASE_WITH_SPACES(new UpperCamelCaseSeparatorNamingPolicy(" ")),
UPPER_CAMEL_CASE_WITH_SPACES() {
public String translateName(Field f) {
return upperCaseFirstLetter(separateCamelCase(f.getName(), " "));
}
},
/**
* 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 an underscore (_).
@ -66,8 +86,12 @@ public enum FieldNamingPolicy {
* <li>aURL ---> a_u_r_l</li>
* </ul>
*/
LOWER_CASE_WITH_UNDERSCORES(new LowerCamelCaseSeparatorNamingPolicy("_")),
LOWER_CASE_WITH_UNDERSCORES() {
public String translateName(Field f) {
return separateCamelCase(f.getName(), "_").toLowerCase();
}
},
/**
* 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 dash (-).
@ -85,15 +109,60 @@ public enum FieldNamingPolicy {
* {@code myobject.my-field} will result in an unintended javascript expression.
* @since 1.4
*/
LOWER_CASE_WITH_DASHES(new LowerCamelCaseSeparatorNamingPolicy("-"));
LOWER_CASE_WITH_DASHES() {
public String translateName(Field f) {
return separateCamelCase(f.getName(), "-").toLowerCase();
}
};
private final FieldNamingStrategy2 namingPolicy;
private FieldNamingPolicy(FieldNamingStrategy2 namingPolicy) {
this.namingPolicy = namingPolicy;
/**
* Converts the field name that uses camel-case define word separation into
* separate words that are separated by the provided {@code separatorString}.
*/
private static String separateCamelCase(String name, String separator) {
StringBuilder translation = new StringBuilder();
for (int i = 0; i < name.length(); i++) {
char character = name.charAt(i);
if (Character.isUpperCase(character) && translation.length() != 0) {
translation.append(separator);
}
translation.append(character);
}
return translation.toString();
}
FieldNamingStrategy2 getFieldNamingPolicy() {
return namingPolicy;
/**
* Ensures the JSON field names begins with an upper case letter.
*/
private static String upperCaseFirstLetter(String name) {
StringBuilder fieldNameBuilder = new StringBuilder();
int index = 0;
char firstCharacter = name.charAt(index);
while (index < name.length() - 1) {
if (Character.isLetter(firstCharacter)) {
break;
}
fieldNameBuilder.append(firstCharacter);
firstCharacter = name.charAt(++index);
}
if (index == name.length()) {
return fieldNameBuilder.toString();
}
if (!Character.isUpperCase(firstCharacter)) {
String modifiedTarget = modifyString(Character.toUpperCase(firstCharacter), name, ++index);
return fieldNameBuilder.append(modifiedTarget).toString();
} else {
return name;
}
}
}
private static String modifyString(char firstCharacter, String srcString, int indexOfSubstring) {
return (indexOfSubstring < srcString.length())
? firstCharacter + srcString.substring(indexOfSubstring)
: String.valueOf(firstCharacter);
}
}

View File

@ -1,37 +0,0 @@
/*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson;
/**
* The new mechanism for providing custom field naming in Gson. This allows the client code
* to translate field names into a particular convention that is not supported as a normal
* Java field declaration rules. For example, Java does not support "-" characters in a
* field name.
*
* @author Inderjeet Singh
* @author Joel Leitch
*/
interface FieldNamingStrategy2 {
/**
* Translates the field name into its JSON field name representation.
*
* @param f the field that is being translated
* @return the translated field name.
*/
public String translateName(FieldAttributes f);
}

View File

@ -1,39 +0,0 @@
/*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson;
import com.google.gson.internal.$Gson$Preconditions;
/**
* Adapts the old FieldNamingStrategy to the new {@link FieldNamingStrategy2}
* type.
*
* @author Inderjeet Singh
* @author Joel Leitch
*/
final class FieldNamingStrategy2Adapter implements FieldNamingStrategy2 {
private final FieldNamingStrategy adaptee;
FieldNamingStrategy2Adapter(FieldNamingStrategy adaptee) {
this.adaptee = $Gson$Preconditions.checkNotNull(adaptee);
}
@SuppressWarnings("deprecation")
public String translateName(FieldAttributes f) {
return adaptee.translateName(f.getFieldObject());
}
}

View File

@ -16,6 +16,7 @@
package com.google.gson;
import com.google.gson.annotations.SerializedName;
import com.google.gson.internal.ConstructorConstructor;
import com.google.gson.internal.Primitives;
import com.google.gson.internal.Streams;
@ -112,8 +113,6 @@ public final class Gson {
new SyntheticFieldExclusionStrategy(true);
static final ModifierBasedExclusionStrategy DEFAULT_MODIFIER_BASED_EXCLUSION_STRATEGY =
new ModifierBasedExclusionStrategy(Modifier.TRANSIENT, Modifier.STATIC);
static final FieldNamingStrategy2 DEFAULT_NAMING_POLICY =
new SerializedNameAnnotationInterceptingNamingPolicy(new JavaFieldNamingPolicy());
private static final ExclusionStrategy DEFAULT_EXCLUSION_STRATEGY = createExclusionStrategy();
@ -200,7 +199,7 @@ public final class Gson {
*/
@SuppressWarnings("unchecked")
public Gson() {
this(DEFAULT_EXCLUSION_STRATEGY, DEFAULT_EXCLUSION_STRATEGY, DEFAULT_NAMING_POLICY,
this(DEFAULT_EXCLUSION_STRATEGY, DEFAULT_EXCLUSION_STRATEGY, FieldNamingPolicy.IDENTITY,
EMPTY_MAP, false, EMPTY_MAP, EMPTY_MAP, false, DEFAULT_JSON_NON_EXECUTABLE, true,
false, false, LongSerializationPolicy.DEFAULT,
Collections.<TypeAdapter.Factory>emptyList());
@ -208,7 +207,7 @@ public final class Gson {
Gson(final ExclusionStrategy deserializationExclusionStrategy,
final ExclusionStrategy serializationExclusionStrategy,
final FieldNamingStrategy2 fieldNamingPolicy,
final FieldNamingStrategy fieldNamingPolicy,
final TypeMap<InstanceCreator<?>> instanceCreators, boolean serializeNulls,
final TypeMap<JsonSerializer<?>> serializers,
final TypeMap<JsonDeserializer<?>> deserializers,
@ -226,18 +225,12 @@ public final class Gson {
this.htmlSafe = htmlSafe;
this.prettyPrinting = prettyPrinting;
/*
TODO: for serialization, honor:
serializationExclusionStrategy
fieldNamingPolicy
serializeNulls
serializers
*/
TypeAdapter.Factory reflectiveTypeAdapterFactory
= new ReflectiveTypeAdapterFactory(constructorConstructor) {
@Override
public String getFieldName(Class<?> declaringClazz, Field f, Type declaredType) {
return fieldNamingPolicy.translateName(new FieldAttributes(declaringClazz, f));
SerializedName serializedName = f.getAnnotation(SerializedName.class);
return serializedName == null ? fieldNamingPolicy.translateName(f) : serializedName.value();
}
@Override
public boolean serializeField(Class<?> declaringClazz, Field f, Type declaredType) {

View File

@ -86,7 +86,7 @@ public final class GsonBuilder {
private boolean serializeInnerClasses;
private boolean excludeFieldsWithoutExposeAnnotation;
private LongSerializationPolicy longSerializationPolicy;
private FieldNamingStrategy2 fieldNamingPolicy;
private FieldNamingStrategy fieldNamingPolicy;
private final TypeMap<InstanceCreator<?>> instanceCreators;
private final TypeMap<JsonSerializer<?>> serializers;
private final TypeMap<JsonDeserializer<?>> deserializers;
@ -123,7 +123,7 @@ public final class GsonBuilder {
modifierBasedExclusionStrategy = Gson.DEFAULT_MODIFIER_BASED_EXCLUSION_STRATEGY;
excludeFieldsWithoutExposeAnnotation = false;
longSerializationPolicy = LongSerializationPolicy.DEFAULT;
fieldNamingPolicy = Gson.DEFAULT_NAMING_POLICY;
fieldNamingPolicy = FieldNamingPolicy.IDENTITY;
instanceCreators = new TypeMap<InstanceCreator<?>>();
serializers = new TypeMap<JsonSerializer<?>>();
deserializers = new TypeMap<JsonDeserializer<?>>();
@ -338,7 +338,8 @@ public final class GsonBuilder {
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
*/
public GsonBuilder setFieldNamingPolicy(FieldNamingPolicy namingConvention) {
return setFieldNamingStrategy(namingConvention.getFieldNamingPolicy());
this.fieldNamingPolicy = namingConvention;
return this;
}
/**
@ -350,19 +351,7 @@ public final class GsonBuilder {
* @since 1.3
*/
public GsonBuilder setFieldNamingStrategy(FieldNamingStrategy fieldNamingStrategy) {
return setFieldNamingStrategy(new FieldNamingStrategy2Adapter(fieldNamingStrategy));
}
/**
* Configures Gson to apply a specific naming policy strategy to an object's field during
* serialization and deserialization.
*
* @param fieldNamingStrategy the actual naming strategy to apply to the fields
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
*/
GsonBuilder setFieldNamingStrategy(FieldNamingStrategy2 fieldNamingStrategy) {
this.fieldNamingPolicy =
new SerializedNameAnnotationInterceptingNamingPolicy(fieldNamingStrategy);
this.fieldNamingPolicy = fieldNamingStrategy;
return this;
}

View File

@ -1,51 +0,0 @@
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Collection;
/**
* A simple implementation of the {@link FieldNamingStrategy2} interface such that it does not
* perform any string translation of the incoming field name.
*
* <p>The following is an example:</p>
*
* <pre>
* class IntWrapper {
* public int integerField = 0;
* }
*
* JavaFieldNamingPolicy policy = new JavaFieldNamingPolicy();
* String translatedFieldName =
* policy.translateName(IntWrapper.class.getField("integerField"));
*
* assert("integerField".equals(translatedFieldName));
* </pre>
*
* <p>This is the default {@link FieldNamingStrategy2} used by Gson.</p>
*
* @author Joel Leitch
*/
final class JavaFieldNamingPolicy extends RecursiveFieldNamingPolicy {
@Override
protected String translateName(String target, Type fieldType, Collection<Annotation> annotations) {
return target;
}
}

View File

@ -1,43 +0,0 @@
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson;
/**
* A {@link FieldNamingStrategy2} that ensures the JSON field names consist of only
* lower case letters and are separated by a particular {@code separatorString}.
*
*<p>The following is an example:</p>
* <pre>
* class StringWrapper {
* public String AStringField = "abcd";
* }
*
* LowerCamelCaseSeparatorNamingPolicy policy = new LowerCamelCaseSeparatorNamingPolicy("_");
* String translatedFieldName =
* policy.translateName(StringWrapper.class.getField("AStringField"));
*
* assert("a_string_field".equals(translatedFieldName));
* </pre>
*
* @author Joel Leitch
*/
final class LowerCamelCaseSeparatorNamingPolicy extends CompositionFieldNamingPolicy {
public LowerCamelCaseSeparatorNamingPolicy(String separatorString) {
super(new CamelCaseSeparatorNamingPolicy(separatorString), new LowerCaseNamingPolicy());
}
}

View File

@ -1,50 +0,0 @@
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Collection;
/**
* A {@link FieldNamingStrategy2} that ensures the JSON field names consist of only
* lower case letters.
*
* <p>The following is an example:</p>
* <pre>
* class IntWrapper {
* public int integerField = 0;
* }
*
* LowerCaseNamingPolicy policy = new LowerCaseNamingPolicy();
* String translatedFieldName =
* policy.translateName(IntWrapper.class.getField("integerField"));
*
* assert("integerfield".equals(translatedFieldName));
* </pre>
*
* @author Inderjeet Singh
* @author Joel Leitch
*/
final class LowerCaseNamingPolicy extends RecursiveFieldNamingPolicy {
@Override
protected String translateName(String target, Type fieldType,
Collection<Annotation> annotations) {
return target.toLowerCase();
}
}

View File

@ -1,108 +0,0 @@
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson;
import com.google.gson.internal.$Gson$Preconditions;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Collection;
/**
* A {@link FieldNamingStrategy2} that ensures the JSON field names begins with
* an upper case letter.
*
*<p>The following is an example:</p>
* <pre>
* class StringWrapper {
* public String stringField = "abcd";
* public String _stringField = "efg";
* }
*
* ModifyFirstLetterNamingPolicy policy =
* new ModifyFirstLetterNamingPolicy(LetterModifier.UPPER);
* String translatedFieldName =
* policy.translateName(StringWrapper.class.getField("stringField"));
*
* assert("StringField".equals(translatedFieldName));
*
* String translatedFieldName =
* policy.translateName(StringWrapper.class.getField("_stringField"));
*
* assert("_StringField".equals(translatedFieldName));
* </pre>
*
* @author Joel Leitch
*/
final class ModifyFirstLetterNamingPolicy extends RecursiveFieldNamingPolicy {
public enum LetterModifier {
UPPER,
LOWER
}
private final LetterModifier letterModifier;
/**
* Creates a new ModifyFirstLetterNamingPolicy that will either modify the first letter of the
* target name to either UPPER case or LOWER case depending on the {@code modifier} parameter.
*
* @param modifier the type of modification that should be performed
* @throws IllegalArgumentException if {@code modifier} is null
*/
ModifyFirstLetterNamingPolicy(LetterModifier modifier) {
this.letterModifier = $Gson$Preconditions.checkNotNull(modifier);
}
@Override
protected String translateName(String target, Type fieldType,
Collection<Annotation> annotations) {
StringBuilder fieldNameBuilder = new StringBuilder();
int index = 0;
char firstCharacter = target.charAt(index);
while (index < target.length() - 1) {
if (Character.isLetter(firstCharacter)) {
break;
}
fieldNameBuilder.append(firstCharacter);
firstCharacter = target.charAt(++index);
}
if (index == target.length()) {
return fieldNameBuilder.toString();
}
boolean capitalizeFirstLetter = (letterModifier == LetterModifier.UPPER);
if (capitalizeFirstLetter && !Character.isUpperCase(firstCharacter)) {
String modifiedTarget = modifyString(Character.toUpperCase(firstCharacter), target, ++index);
return fieldNameBuilder.append(modifiedTarget).toString();
} else if (!capitalizeFirstLetter && Character.isUpperCase(firstCharacter)) {
String modifiedTarget = modifyString(Character.toLowerCase(firstCharacter), target, ++index);
return fieldNameBuilder.append(modifiedTarget).toString();
} else {
return target;
}
}
private String modifyString(char firstCharacter, String srcString, int indexOfSubstring) {
return (indexOfSubstring < srcString.length())
? firstCharacter + srcString.substring(indexOfSubstring)
: String.valueOf(firstCharacter);
}
}

View File

@ -1,45 +0,0 @@
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Collection;
/**
* A mechanism for providing custom field naming in Gson. This allows the client code to translate
* field names into a particular convention that is not supported as a normal Java field
* declaration rules. For example, Java does not support "-" characters in a field name.
*
* @author Joel Leitch
*/
abstract class RecursiveFieldNamingPolicy implements FieldNamingStrategy2 {
public final String translateName(FieldAttributes f) {
return translateName(f.getName(), f.getDeclaredType(), f.getAnnotations());
}
/**
* Performs the specific string translation.
*
* @param target the string object that will be manipulation/translated
* @param fieldType the actual type value of the field
* @param annotations the annotations set on the field
* @return the translated field name
*/
protected abstract String translateName(String target, Type fieldType, Collection<Annotation> annotations);
}

View File

@ -1,48 +0,0 @@
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson;
import com.google.gson.annotations.SerializedName;
/**
* A {@link FieldNamingStrategy2} that acts as a chain of responsibility. If the
* {@link com.google.gson.annotations.SerializedName} annotation is applied to a
* field then this strategy will translate the name to the {@code
* serializedName.value()}; otherwise it delegates to the wrapped
* {@link FieldNamingStrategy2}.
*
* <p>
* NOTE: this class performs JSON field name validation for any of the fields
* marked with an {@code @SerializedName} annotation.
* </p>
*
* @see SerializedName
*
* @author Joel Leitch
*/
final class SerializedNameAnnotationInterceptingNamingPolicy implements FieldNamingStrategy2 {
private final FieldNamingStrategy2 delegate;
SerializedNameAnnotationInterceptingNamingPolicy(FieldNamingStrategy2 delegate) {
this.delegate = delegate;
}
public String translateName(FieldAttributes f) {
SerializedName serializedName = f.getAnnotation(SerializedName.class);
return serializedName == null ? delegate.translateName(f) : serializedName.value();
}
}

View File

@ -1,44 +0,0 @@
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson;
/**
* A {@link FieldNamingStrategy2} that ensures the JSON field names consist of mixed
* case letters starting with a capital and are separated by a particular
* {@code separatorString}.
*
*<p>The following is an example:</p>
* <pre>
* class StringWrapper {
* public String AStringField = "abcd";
* }
*
* UpperCamelCaseSeparatorNamingPolicy policy = new UpperCamelCaseSeparatorNamingPolicy("_");
* String translatedFieldName =
* policy.translateName(StringWrapper.class.getField("AStringField"));
*
* assert("A_String_Field".equals(translatedFieldName));
* </pre>
*
* @author Joel Leitch
*/
final class UpperCamelCaseSeparatorNamingPolicy extends CompositionFieldNamingPolicy {
public UpperCamelCaseSeparatorNamingPolicy(String separatorString) {
super(new CamelCaseSeparatorNamingPolicy(separatorString),
new ModifyFirstLetterNamingPolicy(ModifyFirstLetterNamingPolicy.LetterModifier.UPPER));
}
}

View File

@ -1,48 +0,0 @@
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Collection;
/**
* A {@link FieldNamingStrategy2} that ensures the JSON field names consist of only
* upper case letters.
*
* <p>The following is an example:</p>
* <pre>
* class IntWrapper {
* public int integerField = 0;
* }
*
* UpperCaseNamingPolicy policy = new UpperCaseNamingPolicy();
* String translatedFieldName =
* policy.translateName(IntWrapper.class.getField("integerField"));
*
* assert("INTEGERFIELD".equals(translatedFieldName));
* </pre>
*
* @author Joel Leitch
*/
final class UpperCaseNamingPolicy extends RecursiveFieldNamingPolicy {
@Override
protected String translateName(String target, Type fieldType, Collection<Annotation> annotations) {
return target.toUpperCase();
}
}

View File

@ -1,69 +0,0 @@
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson;
import junit.framework.TestCase;
/**
* Tests for the {@link CamelCaseSeparatorNamingPolicy} class.
*
* @author Joel Leitch
*/
public class CamelCaseSeparatorNamingPolicyTest extends TestCase {
private static final Class<String> CLASS = String.class;
private static final String UNDERSCORE = "_";
private static final String MULTI_CHAR_SEPARATOR = "_$_";
public void testInvalidInstantiation() throws Exception {
try {
new CamelCaseSeparatorNamingPolicy(null);
fail("Null separator string is not supported");
} catch (NullPointerException expected) { }
try {
new CamelCaseSeparatorNamingPolicy("");
fail("Empty separator string is not supported");
} catch (IllegalArgumentException expected) { }
}
public void testUnderscoreSeparator() throws Exception {
CamelCaseSeparatorNamingPolicy namingPolicy =
new CamelCaseSeparatorNamingPolicy(UNDERSCORE);
String translatedName = namingPolicy.translateName("testUnderscoreBetweenWords", CLASS, null);
assertEquals("test_Underscore_Between_Words", translatedName);
}
public void testMultiCharSeparator() throws Exception {
CamelCaseSeparatorNamingPolicy namingPolicy =
new CamelCaseSeparatorNamingPolicy(MULTI_CHAR_SEPARATOR);
String translatedName = namingPolicy.translateName("testMultCharBetweenWords", CLASS, null);
assertEquals("test_$_Mult_$_Char_$_Between_$_Words", translatedName);
}
public void testNameBeginsWithCapital() throws Exception {
CamelCaseSeparatorNamingPolicy namingPolicy = new CamelCaseSeparatorNamingPolicy(UNDERSCORE);
String translatedName = namingPolicy.translateName("TestNameBeginsWithCapital", CLASS, null);
assertEquals("Test_Name_Begins_With_Capital", translatedName);
}
public void testExceptionPossiblyIncorrectSeparation() throws Exception {
CamelCaseSeparatorNamingPolicy namingPolicy = new CamelCaseSeparatorNamingPolicy(UNDERSCORE);
String translatedName = namingPolicy.translateName("aURL", CLASS, null);
assertEquals("a_U_R_L", translatedName);
}
}

View File

@ -1,45 +0,0 @@
/*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson;
import java.lang.reflect.Field;
import junit.framework.TestCase;
/**
* Unit test for the {@link FieldNamingStrategy2Adapter} class.
*
* @author Inderjeet Singh
* @author Joel Leitch
*/
public class FieldNamingStrategy2AdapterTest extends TestCase {
public void testSimpleAdapter() throws Exception {
Field field = String.class.getFields()[0];
String expectedFieldName = field.getName().toUpperCase();
FieldNamingStrategy2 adapter =
new FieldNamingStrategy2Adapter(new UpperCaseNamingStrategy());
assertEquals(expectedFieldName, adapter.translateName(
new FieldAttributes(String.class, field)));
}
private static class UpperCaseNamingStrategy implements FieldNamingStrategy {
public String translateName(Field f) {
return f.getName().toUpperCase();
}
}
}

View File

@ -38,7 +38,7 @@ public class FunctionWithInternalDependenciesTest extends TestCase {
strategies.add(new SyntheticFieldExclusionStrategy(true));
strategies.add(new ModifierBasedExclusionStrategy(Modifier.TRANSIENT, Modifier.STATIC));
ExclusionStrategy exclusionStrategy = new DisjunctionExclusionStrategy(strategies);
Gson gson = new Gson(exclusionStrategy, exclusionStrategy, Gson.DEFAULT_NAMING_POLICY,
Gson gson = new Gson(exclusionStrategy, exclusionStrategy, FieldNamingPolicy.IDENTITY,
Gson.EMPTY_MAP, false, Gson.EMPTY_MAP, Gson.EMPTY_MAP, false,
Gson.DEFAULT_JSON_NON_EXECUTABLE,
true, false, false, LongSerializationPolicy.DEFAULT,

View File

@ -1,47 +0,0 @@
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson;
import junit.framework.TestCase;
/**
* Tests for the {@link JavaFieldNamingPolicy} class.
*
* @author Joel Leitch
*/
public class JavaFieldNamingPolicyTest extends TestCase {
private JavaFieldNamingPolicy namingPolicy;
@Override
protected void setUp() throws Exception {
super.setUp();
namingPolicy = new JavaFieldNamingPolicy();
}
public void testFieldNamingPolicy() throws Exception {
FieldAttributes f = new FieldAttributes(String.class, String.class.getFields()[0]);
assertEquals(f.getName(), namingPolicy.translateName(f));
}
public void testNullField() throws Exception {
try {
namingPolicy.translateName((FieldAttributes) null);
fail("Should have thrown an exception");
} catch (NullPointerException expected) { }
}
}

View File

@ -1,59 +0,0 @@
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson;
import junit.framework.TestCase;
/**
* Tests for the {@link LowerCamelCaseSeparatorNamingPolicy} class.
*
* @author Joel Leitch
*/
public class LowerCamelCaseSeparatorNamingPolicyTest extends TestCase {
private static final Class<String> CLASS = String.class;
private static final String UNDERSCORE = "_";
private LowerCamelCaseSeparatorNamingPolicy namingPolicy;
@Override
protected void setUp() throws Exception {
super.setUp();
namingPolicy = new LowerCamelCaseSeparatorNamingPolicy(UNDERSCORE);
}
public void testNameBeginsWithLowerCase() throws Exception {
String translatedName = namingPolicy.translateName("testNameBeginsWithLower", CLASS, null);
assertEquals("test_name_begins_with_lower", translatedName);
}
public void testNameBeginsWithUpperCase() throws Exception {
String translatedName = namingPolicy.translateName("TestNameBeginsWithUpper", CLASS, null);
assertEquals("test_name_begins_with_upper", translatedName);
}
public void testExceptionPossiblyIncorrectSeparation() throws Exception {
String translatedName = namingPolicy.translateName("aURL", CLASS, null);
assertEquals("a_u_r_l", translatedName);
}
public void testUsingDashesInstead() throws Exception {
namingPolicy = new LowerCamelCaseSeparatorNamingPolicy("-");
String translatedName = namingPolicy.translateName("testUsingDashesInstead", CLASS, null);
assertEquals("test-using-dashes-instead", translatedName);
}
}

View File

@ -1,52 +0,0 @@
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson;
import com.google.gson.LowerCaseNamingPolicy;
import junit.framework.TestCase;
/**
* Tests for the {@link LowerCaseNamingPolicy} class.
*
* @author Joel Leitch
*/
public class LowerCaseNamingPolicyTest extends TestCase {
private static final String ALL_LOWER = "abcdefg";
private static final String ALL_UPPER = "ABCDEFG";
private static final String MIXED = "aBcdeFg";
private LowerCaseNamingPolicy namingPolicy;
@Override
protected void setUp() throws Exception {
super.setUp();
namingPolicy = new LowerCaseNamingPolicy();
}
public void testAllLowerCase() throws Exception {
assertEquals(ALL_LOWER, namingPolicy.translateName(ALL_LOWER, String.class, null));
}
public void testAllUpperCase() throws Exception {
assertEquals(ALL_LOWER, namingPolicy.translateName(ALL_UPPER, String.class, null));
}
public void testMixedCase() throws Exception {
assertEquals(ALL_LOWER, namingPolicy.translateName(MIXED, String.class, null));
}
}

View File

@ -1,87 +0,0 @@
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson;
import junit.framework.TestCase;
/**
* Unit test for the {@link com.google.gson.ModifyFirstLetterNamingPolicy} class.
*
* @author Joel Leitch
*/
public class ModifyFirstLetterNamingPolicyTest extends TestCase {
public void testInvalidConstruction() throws Exception {
try {
new ModifyFirstLetterNamingPolicy(null);
fail("Null values are not allowed as a constructor parameters");
} catch (NullPointerException expected) { }
}
public void testLowerCaseFirstLetter() throws Exception {
ModifyFirstLetterNamingPolicy policy =
new ModifyFirstLetterNamingPolicy(ModifyFirstLetterNamingPolicy.LetterModifier.LOWER);
assertEquals("blah", policy.translateName("Blah", String.class, null));
assertEquals("blah", policy.translateName("blah", String.class, null));
}
public void testUpperCaseFirstLetter() throws Exception {
ModifyFirstLetterNamingPolicy policy =
new ModifyFirstLetterNamingPolicy(ModifyFirstLetterNamingPolicy.LetterModifier.UPPER);
assertEquals("Blah", policy.translateName("blah", String.class, null));
assertEquals("Blah", policy.translateName("Blah", String.class, null));
}
public void testSingleCharacterField() throws Exception {
ModifyFirstLetterNamingPolicy policy =
new ModifyFirstLetterNamingPolicy(ModifyFirstLetterNamingPolicy.LetterModifier.UPPER);
assertEquals("B", policy.translateName("b", String.class, null));
assertEquals("B", policy.translateName("B", String.class, null));
}
public void testFieldStartsWithUnderscore() throws Exception {
ModifyFirstLetterNamingPolicy policy =
new ModifyFirstLetterNamingPolicy(ModifyFirstLetterNamingPolicy.LetterModifier.UPPER);
assertEquals("_Blah", policy.translateName("_blah", String.class, null));
assertEquals("_Blah", policy.translateName("_Blah", String.class, null));
}
public void testFieldStartsWithUnderscoreFollowedBySingleLetter() throws Exception {
ModifyFirstLetterNamingPolicy policy =
new ModifyFirstLetterNamingPolicy(ModifyFirstLetterNamingPolicy.LetterModifier.UPPER);
assertEquals("_B", policy.translateName("_b", String.class, null));
assertEquals("_B", policy.translateName("_B", String.class, null));
}
public void testFieldHasSingleNonLetter() throws Exception {
ModifyFirstLetterNamingPolicy policy =
new ModifyFirstLetterNamingPolicy(ModifyFirstLetterNamingPolicy.LetterModifier.LOWER);
assertEquals("_", policy.translateName("_", String.class, null));
policy = new ModifyFirstLetterNamingPolicy(ModifyFirstLetterNamingPolicy.LetterModifier.UPPER);
assertEquals("_", policy.translateName("_", String.class, null));
}
public void testFieldHasNoLetters() throws Exception {
ModifyFirstLetterNamingPolicy policy =
new ModifyFirstLetterNamingPolicy(ModifyFirstLetterNamingPolicy.LetterModifier.LOWER);
assertEquals("$_$", policy.translateName("$_$", String.class, null));
policy = new ModifyFirstLetterNamingPolicy(ModifyFirstLetterNamingPolicy.LetterModifier.UPPER);
assertEquals("$_$", policy.translateName("$_$", String.class, null));
}
}

View File

@ -1,61 +0,0 @@
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson;
import junit.framework.TestCase;
import com.google.gson.annotations.SerializedName;
/**
* Unit tests for the {@link SerializedNameAnnotationInterceptingNamingPolicy} class.
*
* @author Joel Leitch
*/
public class SerializedNameAnnotationInterceptingNamingPolicyTest extends TestCase {
private static final String ANNOTATED_FIELD_NAME = "annotatedFieldName";
private SerializedNameAnnotationInterceptingNamingPolicy policy;
@Override
protected void setUp() throws Exception {
super.setUp();
policy = new SerializedNameAnnotationInterceptingNamingPolicy(new JavaFieldNamingPolicy());
}
public void testFieldWithAnnotation() throws Exception {
String fieldName = "fieldWithAnnotation";
FieldAttributes f = new FieldAttributes(
SomeObject.class, SomeObject.class.getField(fieldName));
assertFalse(ANNOTATED_FIELD_NAME.equals(fieldName));
assertEquals(ANNOTATED_FIELD_NAME, policy.translateName(f));
}
public void testFieldWithoutAnnotation() throws Exception {
String fieldName = "fieldWithoutAnnotation";
FieldAttributes f = new FieldAttributes(
SomeObject.class, SomeObject.class.getField(fieldName));
assertEquals(fieldName, policy.translateName(f));
}
@SuppressWarnings("unused")
private static class SomeObject {
@SerializedName(ANNOTATED_FIELD_NAME) public final int fieldWithAnnotation = 1;
public final int fieldWithoutAnnotation = 1;
}
}

View File

@ -1,60 +0,0 @@
/*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson;
import junit.framework.TestCase;
/**
* Tests for the {@link UpperCamelCaseSeparatorNamingPolicy} class.
*
* @author Joel Leitch
*/
public class UpperCamelCaseSeparatorNamingPolicyTest extends TestCase {
private UpperCamelCaseSeparatorNamingPolicy namingPolicy;
@Override
protected void setUp() throws Exception {
super.setUp();
namingPolicy = new UpperCamelCaseSeparatorNamingPolicy(" ");
}
public void testAllLowerCase() throws Exception {
assertEquals("Some Field Name",
namingPolicy.translateName("someFieldName", String.class, null));
}
public void testAllUpperCase() throws Exception {
assertEquals("U R L",
namingPolicy.translateName("URL", String.class, null));
}
public void testAllUpperCaseExceptFirst() throws Exception {
assertEquals("U R L",
namingPolicy.translateName("uRL", String.class, null));
}
public void testAllUpperCaseStartingWithUnderscore() throws Exception {
assertEquals("_U R L",
namingPolicy.translateName("_uRL", String.class, null));
}
public void testMixedCase() throws Exception {
assertEquals("_Some Field Name",
namingPolicy.translateName("_someFieldName", String.class, null));
}
}

View File

@ -1,53 +0,0 @@
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson;
import com.google.gson.LowerCaseNamingPolicy;
import com.google.gson.UpperCaseNamingPolicy;
import junit.framework.TestCase;
/**
* Tests for the {@link LowerCaseNamingPolicy} class.
*
* @author Joel Leitch
*/
public class UpperCaseNamingPolicyTest extends TestCase {
private static final String ALL_LOWER = "abcdefg";
private static final String ALL_UPPER = "ABCDEFG";
private static final String MIXED = "aBcdeFg";
private UpperCaseNamingPolicy namingPolicy;
@Override
protected void setUp() throws Exception {
super.setUp();
namingPolicy = new UpperCaseNamingPolicy();
}
public void testAllLowerCase() throws Exception {
assertEquals(ALL_UPPER, namingPolicy.translateName(ALL_LOWER, String.class, null));
}
public void testAllUpperCase() throws Exception {
assertEquals(ALL_UPPER, namingPolicy.translateName(ALL_UPPER, String.class, null));
}
public void testMixedCase() throws Exception {
assertEquals(ALL_UPPER, namingPolicy.translateName(MIXED, String.class, null));
}
}

View File

@ -0,0 +1,80 @@
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson.functional;
import static com.google.gson.FieldNamingPolicy.IDENTITY;
import static com.google.gson.FieldNamingPolicy.LOWER_CASE_WITH_DASHES;
import static com.google.gson.FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES;
import static com.google.gson.FieldNamingPolicy.UPPER_CAMEL_CASE;
import static com.google.gson.FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;
import junit.framework.TestCase;
public final class FieldNamingTest extends TestCase {
public void testIdentity() {
Gson gson = new GsonBuilder().setFieldNamingPolicy(IDENTITY).create();
assertEquals("{'lowerCamel':1,'UpperCamel':2,'_lowerCamelLeadingUnderscore':3," +
"'_UpperCamelLeadingUnderscore':4,'lower_words':5,'UPPER_WORDS':6," +
"'annotatedName':7}",
gson.toJson(new TestNames()).replace('\"', '\''));
}
public void testUpperCamelCase() {
Gson gson = new GsonBuilder().setFieldNamingPolicy(UPPER_CAMEL_CASE).create();
assertEquals("{'LowerCamel':1,'UpperCamel':2,'_LowerCamelLeadingUnderscore':3," +
"'_UpperCamelLeadingUnderscore':4,'Lower_words':5,'UPPER_WORDS':6," +
"'annotatedName':7}",
gson.toJson(new TestNames()).replace('\"', '\''));
}
public void testUpperCamelCaseWithSpaces() {
Gson gson = new GsonBuilder().setFieldNamingPolicy(UPPER_CAMEL_CASE_WITH_SPACES).create();
assertEquals("{'Lower Camel':1,'Upper Camel':2,'_Lower Camel Leading Underscore':3," +
"'_ Upper Camel Leading Underscore':4,'Lower_words':5,'U P P E R_ W O R D S':6," +
"'annotatedName':7}",
gson.toJson(new TestNames()).replace('\"', '\''));
}
public void testLowerCaseWithUnderscores() {
Gson gson = new GsonBuilder().setFieldNamingPolicy(LOWER_CASE_WITH_UNDERSCORES).create();
assertEquals("{'lower_camel':1,'upper_camel':2,'_lower_camel_leading_underscore':3," +
"'__upper_camel_leading_underscore':4,'lower_words':5,'u_p_p_e_r__w_o_r_d_s':6," +
"'annotatedName':7}",
gson.toJson(new TestNames()).replace('\"', '\''));
}
public void testLowerCaseWithDashes() {
Gson gson = new GsonBuilder().setFieldNamingPolicy(LOWER_CASE_WITH_DASHES).create();
assertEquals("{'lower-camel':1,'upper-camel':2,'_lower-camel-leading-underscore':3," +
"'_-upper-camel-leading-underscore':4,'lower_words':5,'u-p-p-e-r_-w-o-r-d-s':6," +
"'annotatedName':7}",
gson.toJson(new TestNames()).replace('\"', '\''));
}
@SuppressWarnings("unused") // fields are used reflectively
private static class TestNames {
int lowerCamel = 1;
int UpperCamel = 2;
int _lowerCamelLeadingUnderscore = 3;
int _UpperCamelLeadingUnderscore = 4;
int lower_words = 5;
int UPPER_WORDS = 6;
@SerializedName("annotatedName") int annotated = 7;
}
}