Changed Gson behavior to reject duplicate fields in a class.

This commit is contained in:
Inderjeet Singh 2011-08-03 03:05:12 +00:00
parent f1f8b666ec
commit 5c620c7e0a
2 changed files with 11 additions and 8 deletions

View File

@ -174,7 +174,11 @@ public final class ReflectiveTypeAdapter<T> extends TypeAdapter<T> {
Type fieldType = $Gson$Types.resolve(type.getType(), raw, field.getGenericType()); Type fieldType = $Gson$Types.resolve(type.getType(), raw, field.getGenericType());
BoundField boundField = createBoundField(context, field, getFieldName(raw, field, declaredType), BoundField boundField = createBoundField(context, field, getFieldName(raw, field, declaredType),
TypeToken.get(fieldType), serialize, deserialize); TypeToken.get(fieldType), serialize, deserialize);
result.put(boundField.name, boundField); BoundField previous = result.put(boundField.name, boundField);
if (previous != null) {
throw new IllegalArgumentException(declaredType
+ " declares multiple JSON fields named " + previous.name);
}
} }
} }
type = TypeToken.get($Gson$Types.resolve(type.getType(), raw, raw.getGenericSuperclass())); type = TypeToken.get($Gson$Types.resolve(type.getType(), raw, raw.getGenericSuperclass()));

View File

@ -103,13 +103,12 @@ public class NamingPolicyTest extends TestCase {
public void testGsonDuplicateNameUsingSerializedNameFieldNamingPolicySerialization() { public void testGsonDuplicateNameUsingSerializedNameFieldNamingPolicySerialization() {
Gson gson = builder.create(); Gson gson = builder.create();
ClassWithDuplicateFields target = new ClassWithDuplicateFields(10); try {
String actual = gson.toJson(target); ClassWithDuplicateFields target = new ClassWithDuplicateFields(10);
assertEquals("{\"a\":10}", actual); gson.toJson(target);
fail();
target = new ClassWithDuplicateFields(3.0D); } catch (IllegalArgumentException expected) {
actual = gson.toJson(target); }
assertEquals("{\"a\":3.0}", actual);
} }
public void testGsonWithUpperCamelCaseSpacesPolicySerialiation() { public void testGsonWithUpperCamelCaseSpacesPolicySerialiation() {