Fixed issue 443 by relying on Streams.parse() to return a JsonNull on empty documents and throw a JsonParseException otherwise.

This commit is contained in:
Inderjeet Singh 2012-06-30 18:48:11 +00:00
parent 1c7aee40f3
commit 582b0a0c9c
4 changed files with 21 additions and 9 deletions

View File

@ -15,14 +15,14 @@
*/
package com.google.gson;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import com.google.gson.internal.Streams;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.MalformedJsonException;
import java.io.EOFException;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
/**
* A parser to parse Json into a parse tree of {@link JsonElement}s
@ -86,11 +86,6 @@ public final class JsonParser {
throw new JsonParseException("Failed parsing JSON source: " + json + " to Json", e);
} catch (OutOfMemoryError e) {
throw new JsonParseException("Failed parsing JSON source: " + json + " to Json", e);
} catch (JsonParseException e) {
if (e.getCause() instanceof EOFException) {
return JsonNull.INSTANCE;
}
throw e;
} finally {
json.setLenient(lenient);
}

View File

@ -50,6 +50,9 @@ public final class Streams {
if (isEmpty) {
return JsonNull.INSTANCE;
}
// We could possibly throw JsonSyntaxException since the stream prematurely ended.
// However, it seems safe to throw JsonIOException since the source is an IOException.
// Another reason is to maintain backward compatibility.
throw new JsonIOException(e);
} catch (MalformedJsonException e) {
throw new JsonSyntaxException(e);

View File

@ -38,6 +38,13 @@ public class JsonParserTest extends TestCase {
parser = new JsonParser();
}
public void testParseInvalidJson() {
try {
parser.parse("[[]");
fail();
} catch (JsonParseException expected) { }
}
public void testParseUnquotedStringArrayFails() {
JsonElement element = parser.parse("[a,b,c]");
assertEquals("a", element.getAsJsonArray().get(0).getAsString());

View File

@ -50,6 +50,13 @@ public class JsonParserTest extends TestCase {
gson = new Gson();
}
public void testParseInvalidJson() {
try {
gson.fromJson("[[]", Object[].class);
fail();
} catch (JsonSyntaxException expected) { }
}
public void testDeserializingCustomTree() {
JsonObject obj = new JsonObject();
obj.addProperty("stringValue", "foo");