Start using JsonElementReader in TypeAdapter.

Also fix strict handling of NaN and Infinity
This commit is contained in:
Jesse Wilson 2011-09-30 03:47:30 +00:00
parent 1bb01055f0
commit 6c0566bd22
3 changed files with 41 additions and 1 deletions

View File

@ -170,6 +170,9 @@ public final class JsonElementReader extends JsonReader {
throw new IllegalStateException("Expected " + JsonToken.NUMBER + " but was " + token);
}
double result = ((JsonPrimitive) peekStack()).getAsDouble();
if (!isLenient() && (Double.isNaN(result) || Double.isInfinite(result))) {
throw new NumberFormatException("JSON forbids NaN and infinities: " + result);
}
popStack();
return result;
}

View File

@ -70,7 +70,7 @@ public abstract class TypeAdapter<T> {
public T fromJsonElement(JsonElement json) {
try {
JsonReader jsonReader = new JsonReader(new StringReader(json.toString()));
JsonReader jsonReader = new JsonElementReader(json);
jsonReader.setLenient(true);
return read(jsonReader);
} catch (IOException e) {

View File

@ -34,6 +34,43 @@ public final class JsonElementReaderTest extends TestCase {
reader.endArray();
}
public void testLenientNansAndInfinities() throws IOException {
JsonElement element = new JsonParser().parse("[NaN, -Infinity, Infinity]");
JsonElementReader reader = new JsonElementReader(element);
reader.setLenient(true);
reader.beginArray();
assertTrue(Double.isNaN(reader.nextDouble()));
assertEquals(Double.NEGATIVE_INFINITY, reader.nextDouble());
assertEquals(Double.POSITIVE_INFINITY, reader.nextDouble());
reader.endArray();
}
public void testStrictNansAndInfinities() throws IOException {
JsonElement element = new JsonParser().parse("[NaN, -Infinity, Infinity]");
JsonElementReader reader = new JsonElementReader(element);
reader.setLenient(false);
reader.beginArray();
try {
reader.nextDouble();
fail();
} catch (NumberFormatException e) {
}
assertEquals("NaN", reader.nextString());
try {
reader.nextDouble();
fail();
} catch (NumberFormatException e) {
}
assertEquals("-Infinity", reader.nextString());
try {
reader.nextDouble();
fail();
} catch (NumberFormatException e) {
}
assertEquals("Infinity", reader.nextString());
reader.endArray();
}
public void testNumbersFromStrings() throws IOException {
JsonElement element = new JsonParser().parse("[\"1\", \"2\", \"3\"]");
JsonElementReader reader = new JsonElementReader(element);