Implemented support for serializing objects of type Bar<Foo> without the need to specify their type explicitly in toJson method.
This commit is contained in:
parent
ef2f73180b
commit
d347128e6f
@ -18,6 +18,7 @@ package com.google.gson;
|
||||
import java.lang.reflect.AccessibleObject;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Type;
|
||||
import java.lang.reflect.TypeVariable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@ -59,7 +60,7 @@ final class ReflectingFieldNavigator {
|
||||
|| exclusionStrategy.shouldSkipClass(fieldAttributes.getDeclaredClass())) {
|
||||
continue; // skip
|
||||
}
|
||||
Type resolvedTypeOfField = fieldAttributes.getResolvedType();
|
||||
Type resolvedTypeOfField = getMoreSpecificType(fieldAttributes.getResolvedType(), obj, fieldAttributes);
|
||||
boolean visitedWithCustomHandler =
|
||||
visitor.visitFieldUsingCustomHandler(fieldAttributes, resolvedTypeOfField, obj);
|
||||
if (!visitedWithCustomHandler) {
|
||||
@ -72,6 +73,20 @@ final class ReflectingFieldNavigator {
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Type getMoreSpecificType(Type type, Object obj, FieldAttributes fieldAttributes) {
|
||||
try {
|
||||
if (obj != null && (Object.class == type || type instanceof TypeVariable)) {
|
||||
Object fieldValue = fieldAttributes.get(obj);
|
||||
if (fieldValue != null) {
|
||||
type = fieldValue.getClass();
|
||||
}
|
||||
}
|
||||
} catch (IllegalAccessException e) {
|
||||
}
|
||||
return type;
|
||||
}
|
||||
|
||||
private List<FieldAttributes> getAllFields(Type type, Type declaredType) {
|
||||
List<FieldAttributes> fields = fieldsCache.getElement(type);
|
||||
if (fields == null) {
|
||||
|
@ -18,7 +18,6 @@ package com.google.gson.functional;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
|
||||
import junit.framework.AssertionFailedError;
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
@ -54,12 +53,11 @@ public class RawSerializationTest extends TestCase {
|
||||
public void testParameterizedObject() {
|
||||
Bar<Foo> bar = new Bar<Foo>(new Foo(1));
|
||||
String expectedJson = "{\"t\":{\"b\":1}}";
|
||||
try {
|
||||
// Ensure that serialization works without specifying the type explicitly
|
||||
String json = gson.toJson(bar);
|
||||
assertEquals(expectedJson, json);
|
||||
} catch (AssertionFailedError expected) {
|
||||
}
|
||||
String json = gson.toJson(bar, new TypeToken<Bar<Foo>>(){}.getType());
|
||||
// Ensure that serialization also works when the type is specified explicitly
|
||||
json = gson.toJson(bar, new TypeToken<Bar<Foo>>(){}.getType());
|
||||
assertEquals(expectedJson, json);
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user