Fix nullSafe() to not infinitely recurse on non-null input.

This commit is contained in:
Jesse Wilson 2011-12-06 15:35:52 +00:00
parent e2e672740a
commit eb2230caf0
2 changed files with 8 additions and 5 deletions

View File

@ -179,7 +179,7 @@ public abstract class TypeAdapter<T> {
* } * }
* }.nullSafe()).create(); * }.nullSafe()).create();
* }</pre> * }</pre>
* Note that we didn't need to check for nulls in our type adapter after we used nullSafe. * Note that we didn't need to check for nulls in our type adapter after we used nullSafe.
*/ */
public TypeAdapter<T> nullSafe() { public TypeAdapter<T> nullSafe() {
return new TypeAdapter<T>() { return new TypeAdapter<T>() {
@ -187,7 +187,7 @@ public abstract class TypeAdapter<T> {
if (value == null) { if (value == null) {
out.nullValue(); out.nullValue();
} else { } else {
write(out, value); TypeAdapter.this.write(out, value);
} }
} }
@Override public T read(JsonReader reader) throws IOException { @Override public T read(JsonReader reader) throws IOException {
@ -195,7 +195,7 @@ public abstract class TypeAdapter<T> {
reader.nextNull(); reader.nextNull();
return null; return null;
} }
return read(reader); return TypeAdapter.this.read(reader);
} }
}; };
} }

View File

@ -164,20 +164,23 @@ public final class StreamingTypeAdaptersTest extends TestCase {
truck.horsePower = 1.0D; truck.horsePower = 1.0D;
truck.passengers = new ArrayList<Person>(); truck.passengers = new ArrayList<Person>();
truck.passengers.add(null); truck.passengers.add(null);
truck.passengers.add(new Person("jesse", 30));
try { try {
gson.toJson(truck, Truck.class); gson.toJson(truck, Truck.class);
fail(); fail();
} catch (NullPointerException expected) {} } catch (NullPointerException expected) {}
String json = "{horsePower:1.0,passengers:[null,null]}"; String json = "{horsePower:1.0,passengers:[null,'jesse,30']}";
try { try {
gson.fromJson(json, Truck.class); gson.fromJson(json, Truck.class);
fail(); fail();
} catch (JsonSyntaxException expected) {} } catch (JsonSyntaxException expected) {}
gson = new GsonBuilder().registerTypeAdapter(Person.class, typeAdapter.nullSafe()).create(); gson = new GsonBuilder().registerTypeAdapter(Person.class, typeAdapter.nullSafe()).create();
assertEquals("{\"horsePower\":1.0,\"passengers\":[null]}", gson.toJson(truck, Truck.class)); assertEquals("{\"horsePower\":1.0,\"passengers\":[null,\"jesse,30\"]}",
gson.toJson(truck, Truck.class));
truck = gson.fromJson(json, Truck.class); truck = gson.fromJson(json, Truck.class);
assertEquals(1.0D, truck.horsePower); assertEquals(1.0D, truck.horsePower);
assertNull(truck.passengers.get(0)); assertNull(truck.passengers.get(0));
assertEquals("jesse", truck.passengers.get(1).name);
} }
public void testSerializeRecursive() throws IOException { public void testSerializeRecursive() throws IOException {