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());
BoundField boundField = createBoundField(context, field, getFieldName(raw, field, declaredType),
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()));

View File

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