- Serializing of Object arrays.

- Fixed incorrect warning
This commit is contained in:
Joel Leitch 2009-09-22 19:04:27 +00:00
parent 82771f006c
commit 18b301dfeb
24 changed files with 103 additions and 96 deletions

View File

@ -319,7 +319,6 @@ public final class GsonBuilder {
* {@link JsonSerializer}, and a {@link JsonDeserializer} interfaces.
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
*/
@SuppressWarnings("unchecked")
public GsonBuilder registerTypeAdapter(Type type, Object typeAdapter) {
Preconditions.checkArgument(typeAdapter instanceof JsonSerializer
|| typeAdapter instanceof JsonDeserializer || typeAdapter instanceof InstanceCreator);

View File

@ -144,6 +144,10 @@ final class JsonSerializationVisitor implements ObjectNavigator.Visitor {
@SuppressWarnings("unchecked")
public boolean visitUsingCustomHandler(Object obj, Type objType) {
JsonSerializer serializer = serializers.getHandlerFor(objType);
if (serializer == null && obj != null) {
serializer = serializers.getHandlerFor(obj.getClass());
}
if (serializer != null) {
if (obj == null) {
assignToRoot(JsonNull.createJsonNull());

View File

@ -108,15 +108,20 @@ final class ObjectNavigator {
try {
if (objTypeInfo.isArray()) {
visitor.visitArray(objectToVisit, objType);
} else if (objTypeInfo.getActualType() == Object.class) {
} else if (objTypeInfo.getActualType() == Object.class
&& isPrimitiveOrString(objectToVisit)) {
// TODO(Joel): this is only used for deserialization of "primitves"
// we should rethink this!!!
visitor.visitPrimitive(objectToVisit);
objectToVisit = visitor.getTarget();
} else {
visitor.startVisitingObject(objectToVisit);
// For all classes in the inheritance hierarchy (including the current class),
// visit all fields
for (Class<?> curr = objTypeInfo.getRawClass();
curr != null && !curr.equals(Object.class); curr = curr.getSuperclass()) {
Class<?> topLevelClass = (objTypeInfo.getRawClass() == Object.class)
? objectToVisit.getClass() : objTypeInfo.getRawClass();
for (Class<?> curr = topLevelClass; curr != null && !curr.equals(Object.class);
curr = curr.getSuperclass()) {
if (!curr.isSynthetic()) {
navigateClassFields(objectToVisit, curr, visitor);
}
@ -128,6 +133,12 @@ final class ObjectNavigator {
}
}
private boolean isPrimitiveOrString(Object objectToVisit) {
Class<?> realClazz = objectToVisit.getClass();
return realClazz == Object.class || realClazz == String.class
|| Primitives.unwrap(realClazz).isPrimitive();
}
private void navigateClassFields(Object obj, Class<?> clazz, Visitor visitor) {
Field[] fields = clazz.getDeclaredFields();
AccessibleObject.setAccessible(fields, true);
@ -138,7 +149,7 @@ final class ObjectNavigator {
TypeInfo fieldTypeInfo = TypeInfoFactory.getTypeInfoForField(f, objType);
Type actualTypeOfField = fieldTypeInfo.getActualType();
boolean visitedWithCustomHandler =
visitor.visitFieldUsingCustomHandler(f, actualTypeOfField, obj);
visitor.visitFieldUsingCustomHandler(f, actualTypeOfField, obj);
if (!visitedWithCustomHandler) {
if (fieldTypeInfo.isArray()) {
visitor.visitArrayField(f, actualTypeOfField, obj);

View File

@ -55,7 +55,6 @@ final class TypeInfoFactory {
return new TypeInfo(actualType);
}
@SuppressWarnings("unchecked")
private static Type getActualType(
Type typeToEvaluate, Type parentType, Class<?> rawParentClass) {
if (typeToEvaluate instanceof Class) {

View File

@ -31,7 +31,6 @@ final class TypeInfoMap {
private final Type keyType;
private final Type valueType;
@SuppressWarnings("unchecked")
public TypeInfoMap(Type mapType) {
if (mapType instanceof Class && Properties.class.isAssignableFrom((Class<?>) mapType)) {
keyType = String.class;

View File

@ -40,7 +40,6 @@ final class TypeUtils {
* </pre>
* <code>TypeUtils.getActualTypeForFirstTypeVariable(fooType)</code> will return Integer.class.
*/
@SuppressWarnings("unchecked")
static Type getActualTypeForFirstTypeVariable(Type type) {
if (type instanceof Class) {
return Object.class;
@ -54,7 +53,6 @@ final class TypeUtils {
}
}
@SuppressWarnings("unchecked")
static boolean isArray(Type type) {
if (type instanceof Class) {
return ((Class<?>)type).isArray();
@ -68,7 +66,6 @@ final class TypeUtils {
/**
* This method returns the actual raw class associated with the specified type.
*/
@SuppressWarnings("unchecked")
static Class<?> toRawClass(Type type) {
if (type instanceof Class) {
return (Class<?>) type;

View File

@ -85,7 +85,6 @@ public abstract class TypeToken<T> {
/**
* Gets type from super class's type parameter.
*/
@SuppressWarnings("unchecked")
static Type getSuperclassTypeParameter(Class<?> subclass) {
Type superclass = subclass.getGenericSuperclass();
if (superclass instanceof Class) {
@ -155,7 +154,6 @@ public abstract class TypeToken<T> {
/**
* Check if this type is assignable from the given Type.
*/
@SuppressWarnings("unchecked")
public boolean isAssignableFrom(Type from) {
if (from == null) {
return false;
@ -190,7 +188,6 @@ public abstract class TypeToken<T> {
* Private helper function that performs some assignability checks for
* the provided GenericArrayType.
*/
@SuppressWarnings("unchecked")
private static boolean isAssignableFrom(Type from, GenericArrayType to) {
Type toGenericComponentType = to.getGenericComponentType();
if (toGenericComponentType instanceof ParameterizedType) {
@ -216,7 +213,6 @@ public abstract class TypeToken<T> {
* Private recursive helper function to actually do the type-safe checking
* of assignability.
*/
@SuppressWarnings("unchecked")
private static boolean isAssignableFrom(Type from, ParameterizedType to,
Map<String, Type> typeVarMap) {
@ -293,7 +289,6 @@ public abstract class TypeToken<T> {
* Checks if two types are the same or are equivalent under a variable mapping
* given in the type map that was provided.
*/
@SuppressWarnings("unchecked")
private static boolean matches(Type from, Type to,
Map<String, Type> typeMap) {
if (to.equals(from)) return true;

View File

@ -51,7 +51,6 @@ public class ExposeAnnotationBasedExclusionStrategyTest extends TestCase {
assertFalse(strategy.shouldSkipField(f));
}
@SuppressWarnings("unused")
private static class MockObject {
@Expose
public final int exposedField = 0;

View File

@ -53,7 +53,6 @@ public class SerializedNameAnnotationInterceptingNamingPolicyTest extends TestCa
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

@ -223,7 +223,6 @@ public class TypeInfoFactoryTest extends TestCase {
assertEquals(List[].class, typeInfo.getRawClass());
}
@SuppressWarnings("unused")
private static class ObjectWithDifferentFields<T> {
public static enum TestEnum {
TEST_1, TEST_2;

View File

@ -66,7 +66,7 @@ public class VersionExclusionStrategyTest extends TestCase {
@Since(VERSION)
private static class MockObject {
@SuppressWarnings("unused")
@Since(VERSION)
public final int someField = 0;
}

View File

@ -21,12 +21,14 @@ import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import com.google.gson.common.MoreAsserts;
import com.google.gson.common.TestTypes.BagOfPrimitives;
import com.google.gson.common.TestTypes.ClassWithObjects;
import com.google.gson.common.TestTypes.CrazyLongTypeAdapter;
import com.google.gson.reflect.TypeToken;
import junit.framework.TestCase;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
@ -179,4 +181,50 @@ public class ArrayTest extends TestCase {
assertEquals(1, deserializedValue.length);
assertEquals(value[0], deserializedValue[0]);
}
public void testArrayOfPrimitivesAsObjectsSerialization() throws Exception {
Object[] objs = new Object[]{1, "abc", 0.3f, 5L};
String json = gson.toJson(objs);
assertTrue(json.contains("abc"));
assertTrue(json.contains("0.3"));
assertTrue(json.contains("5"));
}
public void testArrayOfPrimitivesAsObjectsDeserialization() throws Exception {
String json = "[1,'abc',0.3,5]";
Object[] objs = gson.fromJson(json, Object[].class);
assertEquals(1, objs[0]);
assertEquals("abc", objs[1]);
assertEquals(new BigDecimal("0.3"), objs[2]);
assertEquals(5, objs[3]);
}
public void testArrayOfObjectsWithoutTypeInfoDeserialization() throws Exception {
String json = "[1,'abc',{a:1},5]";
try {
gson.fromJson(json, Object[].class);
} catch (JsonParseException expected) {
}
}
public void testArrayWithoutTypeInfoDeserialization() throws Exception {
String json = "[1,'abc',[1,2],5]";
try {
gson.fromJson(json, Object[].class);
} catch (JsonParseException expected) {
}
}
public void testObjectArrayWithNonPrimitivesSerializaiton() throws Exception {
ClassWithObjects classWithObjects = new ClassWithObjects();
BagOfPrimitives bagOfPrimitives = new BagOfPrimitives();
String classWithObjectsJson = gson.toJson(classWithObjects);
String bagOfPrimitivesJson = gson.toJson(bagOfPrimitives);
Object[] objects = new Object[] { classWithObjects, bagOfPrimitives };
String json = gson.toJson(objects);
assertTrue(json.contains(classWithObjectsJson));
assertTrue(json.contains(bagOfPrimitivesJson));
}
}

View File

@ -283,7 +283,7 @@ public class CollectionTest extends TestCase {
private static class ObjectWithWildcardCollection {
private final Collection<? extends BagOfPrimitives> collection;
@SuppressWarnings({ "unchecked", "unused" })
@SuppressWarnings("unchecked")
public ObjectWithWildcardCollection() {
this(Collections.EMPTY_LIST);
}
@ -300,7 +300,6 @@ public class CollectionTest extends TestCase {
private static class Entry {
int value;
// For use by Gson
@SuppressWarnings("unused")
Entry() {
this(10);
}

View File

@ -120,8 +120,7 @@ public class ConcurrencyTest extends TestCase {
finishedLatch.await();
assertFalse(failed.get());
}
@SuppressWarnings("unused")
private static class MyObject {
String a;
String b;

View File

@ -65,7 +65,6 @@ public class CustomDeserializerTest extends TestCase {
private static class DataHolder {
private final String data;
@SuppressWarnings("unused")
public DataHolder() {
throw new IllegalStateException();
}
@ -82,7 +81,6 @@ public class CustomDeserializerTest extends TestCase {
private static class DataHolderWrapper {
private final DataHolder wrappedData;
@SuppressWarnings("unused")
public DataHolderWrapper() {
this(new DataHolder(DEFAULT_VALUE));
}

View File

@ -289,7 +289,6 @@ public class DefaultTypeAdaptersTest extends TestCase {
private static class ClassWithBigDecimal {
BigDecimal value;
@SuppressWarnings("unused")
ClassWithBigDecimal() { }
ClassWithBigDecimal(String value) {
this.value = new BigDecimal(value);
@ -301,7 +300,6 @@ public class DefaultTypeAdaptersTest extends TestCase {
private static class ClassWithBigInteger {
BigInteger value;
@SuppressWarnings("unused")
ClassWithBigInteger() { }
ClassWithBigInteger(String value) {
this.value = new BigInteger(value);

View File

@ -117,7 +117,6 @@ public class ExposeFieldsTest extends TestCase {
@Expose(deserialize = false) final double d;
@Expose(serialize = false, deserialize = false) final char e;
@SuppressWarnings("unused")
ClassWithExposedFields() {
this(null, null);
}
@ -166,8 +165,7 @@ public class ExposeFieldsTest extends TestCase {
private static class ClassWithInterfaceField {
@Expose
private final SomeInterface interfaceField;
@SuppressWarnings("unused")
public ClassWithInterfaceField() {
this(null);
}

View File

@ -75,7 +75,6 @@ public class JsonTreeTest extends TestCase {
}
private static class SubTypeOfBagOfPrimitives extends BagOfPrimitives {
@SuppressWarnings("unused")
float f = 1.2F;
public SubTypeOfBagOfPrimitives(long l, int i, boolean b, String string, float f) {
super(l, i, b, string);

View File

@ -172,7 +172,6 @@ public class MapTest extends TestCase {
private static class MyParameterizedMap<K, V> extends LinkedHashMap<K, V> {
private static final long serialVersionUID = 1L;
@SuppressWarnings("unused")
int foo = 10;
}
@ -249,7 +248,6 @@ public class MapTest extends TestCase {
private static class MyMap extends LinkedHashMap<String, String> {
private static final long serialVersionUID = 1L;
@SuppressWarnings("unused")
int foo = 10;
}

View File

@ -81,8 +81,7 @@ public class NamingPolicyTest extends TestCase {
actual = gson.toJson(target);
assertEquals("{\"a\":3.0}", actual);
}
@SuppressWarnings("unused")
private static class ClassWithDuplicateFields {
public Integer a;
@SerializedName("a") public Double b;

View File

@ -151,7 +151,6 @@ public class NullObjectAndFieldTest extends TestCase {
private Long value;
}
@SuppressWarnings("unused")
private static class ClassWithMembers {
String str;
int[] array;

View File

@ -16,10 +16,21 @@
package com.google.gson.functional;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import junit.framework.TestCase;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.InstanceCreator;
import com.google.gson.JsonParseException;
import com.google.gson.common.TestTypes.ArrayOfObjects;
import com.google.gson.common.TestTypes.BagOfPrimitiveWrappers;
import com.google.gson.common.TestTypes.BagOfPrimitives;
@ -31,19 +42,6 @@ import com.google.gson.common.TestTypes.ClassWithTransientFields;
import com.google.gson.common.TestTypes.Nested;
import com.google.gson.common.TestTypes.PrimitiveArray;
import junit.framework.TestCase;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
/**
* Functional tests for Json serialization and deserialization of regular classes.
*
@ -257,6 +255,22 @@ public class ObjectTest extends TestCase {
assertTrue(target.sortedSetContains('a', 'b', 'c', 'd'));
}
public void testArrayOfObjectsAsFields() throws Exception {
ClassWithObjects classWithObjects = new ClassWithObjects();
BagOfPrimitives bagOfPrimitives = new BagOfPrimitives();
String stringValue = "someStringValueInArray";
String classWithObjectsJson = gson.toJson(classWithObjects);
String bagOfPrimitivesJson = gson.toJson(bagOfPrimitives);
ClassWithArray classWithArray = new ClassWithArray(
new Object[] { stringValue, classWithObjects, bagOfPrimitives });
String json = gson.toJson(classWithArray);
assertTrue(json.contains(classWithObjectsJson));
assertTrue(json.contains(bagOfPrimitivesJson));
assertTrue(json.contains("\"" + stringValue + "\""));
}
/**
* Created in response to Issue 14: http://code.google.com/p/google-gson/issues/detail?id=14
*/
@ -350,8 +364,7 @@ public class ObjectTest extends TestCase {
String json = gson.toJson(obj);
assertTrue(json.contains("abc"));
}
@SuppressWarnings("unused")
private static class ClassWithObjectField {
Object member;
}
@ -378,7 +391,6 @@ public class ObjectTest extends TestCase {
}
private static class Parent {
@SuppressWarnings("unused")
int value1 = 1;
private class Child {
int value2 = 2;
@ -392,7 +404,6 @@ public class ObjectTest extends TestCase {
private SortedSet<Character> sortedSet;
// For use by Gson
@SuppressWarnings("unused")
ClassWithSubInterfacesOfCollection() {
}
@ -485,7 +496,6 @@ public class ObjectTest extends TestCase {
private static class SubTypeOfNested extends Nested {
private final long value = 5;
@SuppressWarnings("unused")
public SubTypeOfNested() {
this(null, null);
}
@ -569,39 +579,6 @@ public class ObjectTest extends TestCase {
bag = gson.fromJson(json, BagOfPrimitives.class);
assertEquals("true", bag.stringValue);
}
public void testArrayOfPrimitivesAsObjectsSerialization() {
Object[] objs = new Object[]{1, "abc", 0.3f, 5L};
String json = gson.toJson(objs);
assertTrue(json.contains("abc"));
assertTrue(json.contains("0.3"));
assertTrue(json.contains("5"));
}
public void testArrayOfPrimitivesAsObjectsDeserialization() {
String json = "[1,'abc',0.3,5]";
Object[] objs = gson.fromJson(json, Object[].class);
assertEquals(1, objs[0]);
assertEquals("abc", objs[1]);
assertEquals(new BigDecimal("0.3"), objs[2]);
assertEquals(5, objs[3]);
}
public void testArrayOfObjectsWithoutTypeInfoDeserialization() {
String json = "[1,'abc',{a:1},5]";
try {
gson.fromJson(json, Object[].class);
} catch (JsonParseException expected) {
}
}
public void testArrayWithoutTypeInfoDeserialization() {
String json = "[1,'abc',[1,2],5]";
try {
gson.fromJson(json, Object[].class);
} catch (JsonParseException expected) {
}
}
/**
* Created to reproduce issue 140

View File

@ -271,7 +271,6 @@ public class ParameterizedTypesTest extends TestCase {
private final List<? extends T> listOfWildcardTypeParameters;
private final List<? extends T>[] arrayOfListOfWildcardTypeParameters;
@SuppressWarnings("unused")
public ObjectWithTypeVariables() {
this(null, null, null, null, null, null);
}
@ -387,7 +386,6 @@ public class ParameterizedTypesTest extends TestCase {
C c;
D d;
E e;
@SuppressWarnings("unused")
MultiParameters() {
}
MultiParameters(A a, B b, C c, D d, E e) {
@ -463,11 +461,9 @@ public class ParameterizedTypesTest extends TestCase {
// Begin: tests to reproduce issue 103
private static class Quantity {
@SuppressWarnings("unused")
int q = 10;
}
private static class MyQuantity extends Quantity {
@SuppressWarnings("unused")
int q2 = 20;
}
private interface Measurable<T> {

View File

@ -72,7 +72,6 @@ public class PerformanceTest extends TestCase {
private static class ExceptionHolder {
public final String message;
public final String stackTrace;
@SuppressWarnings("unused")
public ExceptionHolder() {
this("", "");
}
@ -82,15 +81,14 @@ public class PerformanceTest extends TestCase {
}
}
@SuppressWarnings("unused")
private static class CollectionEntry {
final String name;
final String value;
CollectionEntry() {
this(null, null);
}
CollectionEntry(String name, String value) {
this.name = name;
this.value = value;