Fix JsonTreeReader throwing wrong exception type for non-finite doubles (#1782)

Follow-up for #1767
This commit is contained in:
Marcono1234 2022-08-08 15:39:29 +02:00 committed by GitHub
parent f7cefcb426
commit a4bc6c17d7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 8 additions and 4 deletions

View File

@ -213,7 +213,7 @@ public final class JsonTreeReader extends JsonReader {
}
double result = ((JsonPrimitive) peekStack()).getAsDouble();
if (!isLenient() && (Double.isNaN(result) || Double.isInfinite(result))) {
throw new NumberFormatException("JSON forbids NaN and infinities: " + result);
throw new MalformedJsonException("JSON forbids NaN and infinities: " + result);
}
popStack();
if (stackSize > 0) {

View File

@ -20,6 +20,7 @@ import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.MalformedJsonException;
import java.io.IOException;
import junit.framework.TestCase;
@ -55,19 +56,22 @@ public final class JsonElementReaderTest extends TestCase {
try {
reader.nextDouble();
fail();
} catch (NumberFormatException e) {
} catch (MalformedJsonException e) {
assertEquals("JSON forbids NaN and infinities: NaN", e.getMessage());
}
assertEquals("NaN", reader.nextString());
try {
reader.nextDouble();
fail();
} catch (NumberFormatException e) {
} catch (MalformedJsonException e) {
assertEquals("JSON forbids NaN and infinities: -Infinity", e.getMessage());
}
assertEquals("-Infinity", reader.nextString());
try {
reader.nextDouble();
fail();
} catch (NumberFormatException e) {
} catch (MalformedJsonException e) {
assertEquals("JSON forbids NaN and infinities: Infinity", e.getMessage());
}
assertEquals("Infinity", reader.nextString());
reader.endArray();