Implemented support for multiple values for SerializedName annotation.

This commit is contained in:
Inderjeet Singh 2015-10-03 02:01:16 -07:00
parent 3361030766
commit 109915d93a
5 changed files with 118 additions and 25 deletions

View File

@ -3,7 +3,7 @@
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<packaging>jar</packaging>
<version>2.3.2-SNAPSHOT</version>
<version>2.4-SNAPSHOT</version>
<inceptionYear>2008</inceptionYear>
<name>Gson</name>
<parent>

View File

@ -33,13 +33,15 @@ import java.lang.annotation.Target;
*
* <p>Here is an example of how this annotation is meant to be used:</p>
* <pre>
* public class SomeClassWithFields {
* &#64SerializedName("name") private final String someField;
* private final String someOtherField;
* public class MyClass {
* &#64SerializedName("name") String a;
* &#64SerializedName(value="name1", alternate={"name2", "name3"}) String b;
* String c;
*
* public SomeClassWithFields(String a, String b) {
* this.someField = a;
* this.someOtherField = b;
* public MyClass(String a, String b, String c) {
* this.a = a;
* this.b = b;
* this.c = c;
* }
* }
* </pre>
@ -47,16 +49,27 @@ import java.lang.annotation.Target;
* <p>The following shows the output that is generated when serializing an instance of the
* above example class:</p>
* <pre>
* SomeClassWithFields objectToSerialize = new SomeClassWithFields("a", "b");
* MyClass target = new MyClass("v1", "v2", "v3");
* Gson gson = new Gson();
* String jsonRepresentation = gson.toJson(objectToSerialize);
* System.out.println(jsonRepresentation);
* String json = gson.toJson(target);
* System.out.println(json);
*
* ===== OUTPUT =====
* {"name":"a","someOtherField":"b"}
* {"name":"v1","name1":"v2","c":"v3"}
* </pre>
*
* <p>NOTE: The value you specify in this annotation must be a valid JSON field name.</p>
* While deserializing, all values specified in the annotation will be deserialized into the field.
* For example:
* <pre>
* MyClass target = gson.fromJson("{'name1':'v1'}", MyClass.class);
* assertEquals("v1", target.b);
* target = gson.fromJson("{'name2':'v2'}", MyClass.class);
* assertEquals("v2", target.b);
* target = gson.fromJson("{'name3':'v3'}", MyClass.class);
* assertEquals("v3", target.b);
* </pre>
* Note that MyClass.b is now deserialized from either name1, name2 or name3.
*
* @see com.google.gson.FieldNamingPolicy
*
@ -68,7 +81,9 @@ import java.lang.annotation.Target;
public @interface SerializedName {
/**
* @return the desired name of the field when it is serialized
* @return the desired names of the field when it is deserialized or serialized. All of the specified names will be deserialized from.
* The specified first name is what is used for serialization.
*/
String value();
String[] alternate() default {};
}

View File

@ -16,6 +16,16 @@
package com.google.gson.internal.bind;
import static com.google.gson.internal.bind.JsonAdapterAnnotationTypeAdapterFactory.getTypeAdapter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import com.google.gson.FieldNamingStrategy;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
@ -32,13 +42,6 @@ import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.LinkedHashMap;
import java.util.Map;
import static com.google.gson.internal.bind.JsonAdapterAnnotationTypeAdapterFactory.getTypeAdapter;
/**
* Type adapter that reflects over the fields and methods of a class.
@ -63,13 +66,24 @@ public final class ReflectiveTypeAdapterFactory implements TypeAdapterFactory {
return !excluder.excludeClass(f.getType(), serialize) && !excluder.excludeField(f, serialize);
}
private String getFieldName(Field f) {
/** first element holds the default name */
private List<String> getFieldNames(Field f) {
return getFieldName(fieldNamingPolicy, f);
}
static String getFieldName(FieldNamingStrategy fieldNamingPolicy, Field f) {
/** first element holds the default name */
static List<String> getFieldName(FieldNamingStrategy fieldNamingPolicy, Field f) {
SerializedName serializedName = f.getAnnotation(SerializedName.class);
return serializedName == null ? fieldNamingPolicy.translateName(f) : serializedName.value();
List<String> fieldNames = new LinkedList<String>();
if (serializedName == null) {
fieldNames.add(fieldNamingPolicy.translateName(f));
} else {
fieldNames.add(serializedName.value());
for (String alternate : serializedName.alternate()) {
fieldNames.add(alternate);
}
}
return fieldNames;
}
public <T> TypeAdapter<T> create(Gson gson, final TypeToken<T> type) {
@ -139,9 +153,16 @@ public final class ReflectiveTypeAdapterFactory implements TypeAdapterFactory {
}
field.setAccessible(true);
Type fieldType = $Gson$Types.resolve(type.getType(), raw, field.getGenericType());
BoundField boundField = createBoundField(context, field, getFieldName(field),
TypeToken.get(fieldType), serialize, deserialize);
BoundField previous = result.put(boundField.name, boundField);
List<String> fieldNames = getFieldNames(field);
BoundField previous = null;
for (int i = 0; i < fieldNames.size(); ++i) {
String name = fieldNames.get(i);
if (i != 0) serialize = false; // only serialize the default name
BoundField boundField = createBoundField(context, field, name,
TypeToken.get(fieldType), serialize, deserialize);
BoundField replaced = result.put(name, boundField);
if (previous == null) previous = replaced;
}
if (previous != null) {
throw new IllegalArgumentException(declaredType
+ " declares multiple JSON fields named " + previous.name);

View File

@ -727,6 +727,9 @@ public final class TypeAdapters {
SerializedName annotation = classOfT.getField(name).getAnnotation(SerializedName.class);
if (annotation != null) {
name = annotation.value();
for (String alternate : annotation.alternate()) {
nameToConstant.put(alternate, constant);
}
}
nameToConstant.put(name, constant);
constantToName.put(constant, name);

View File

@ -0,0 +1,54 @@
/*
* Copyright (C) 2015 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 com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import junit.framework.TestCase;
public final class SerializedNameTest extends TestCase {
private final Gson gson = new Gson();
public void testFirstNameIsChosenForSerialization() {
MyClass target = new MyClass("v1", "v2");
// Ensure name1 occurs exactly once, and name2 and name3 dont appear
assertEquals("{\"name\":\"v1\",\"name1\":\"v2\"}", gson.toJson(target));
}
public void testMultipleNamesDeserializedCorrectly() {
assertEquals("v1", gson.fromJson("{'name':'v1'}", MyClass.class).a);
// Both name1 and name2 gets deserialized to b
assertEquals("v11", gson.fromJson("{'name1':'v11'}", MyClass.class).b);
assertEquals("v2", gson.fromJson("{'name2':'v2'}", MyClass.class).b);
assertEquals("v3", gson.fromJson("{'name3':'v3'}", MyClass.class).b);
}
public void testMultipleNamesInTheSameString() {
// The last value takes precedence
assertEquals("v3", gson.fromJson("{'name1':'v1','name2':'v2','name3':'v3'}", MyClass.class).b);
}
private static final class MyClass {
@SerializedName("name") String a;
@SerializedName(value="name1", alternate={"name2", "name3"}) String b;
MyClass(String a, String b) {
this.a = a;
this.b = b;
}
}
}