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();
* }</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() {
return new TypeAdapter<T>() {
@ -187,7 +187,7 @@ public abstract class TypeAdapter<T> {
if (value == null) {
out.nullValue();
} else {
write(out, value);
TypeAdapter.this.write(out, value);
}
}
@Override public T read(JsonReader reader) throws IOException {
@ -195,7 +195,7 @@ public abstract class TypeAdapter<T> {
reader.nextNull();
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.passengers = new ArrayList<Person>();
truck.passengers.add(null);
truck.passengers.add(new Person("jesse", 30));
try {
gson.toJson(truck, Truck.class);
fail();
} catch (NullPointerException expected) {}
String json = "{horsePower:1.0,passengers:[null,null]}";
String json = "{horsePower:1.0,passengers:[null,'jesse,30']}";
try {
gson.fromJson(json, Truck.class);
fail();
} catch (JsonSyntaxException expected) {}
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);
assertEquals(1.0D, truck.horsePower);
assertNull(truck.passengers.get(0));
assertEquals("jesse", truck.passengers.get(1).name);
}
public void testSerializeRecursive() throws IOException {