Refactor JsonParser to statics & fix tests

This commit is contained in:
Degubi 2019-04-15 23:25:40 +02:00 committed by Jake Wharton
parent 477b3f77e1
commit c5a3f21fba
6 changed files with 64 additions and 52 deletions

View File

@ -32,6 +32,9 @@ import com.google.gson.stream.MalformedJsonException;
* @since 1.3 * @since 1.3
*/ */
public final class JsonParser { public final class JsonParser {
/** @deprecated No need to instantiate this class, use the static methods instead. */
@Deprecated
public JsonParser() {}
/** /**
* Parses the specified JSON string into a parse tree * Parses the specified JSON string into a parse tree
@ -39,24 +42,22 @@ public final class JsonParser {
* @param json JSON text * @param json JSON text
* @return a parse tree of {@link JsonElement}s corresponding to the specified JSON * @return a parse tree of {@link JsonElement}s corresponding to the specified JSON
* @throws JsonParseException if the specified text is not valid JSON * @throws JsonParseException if the specified text is not valid JSON
* @since 1.3
*/ */
public JsonElement parse(String json) throws JsonSyntaxException { public static JsonElement parseString(String json) throws JsonSyntaxException {
return parse(new StringReader(json)); return parseReader(new StringReader(json));
} }
/** /**
* Parses the specified JSON string into a parse tree * Parses the specified JSON string into a parse tree
* *
* @param json JSON text * @param reader JSON text
* @return a parse tree of {@link JsonElement}s corresponding to the specified JSON * @return a parse tree of {@link JsonElement}s corresponding to the specified JSON
* @throws JsonParseException if the specified text is not valid JSON * @throws JsonParseException if the specified text is not valid JSON
* @since 1.3
*/ */
public JsonElement parse(Reader json) throws JsonIOException, JsonSyntaxException { public static JsonElement parseReader(Reader reader) throws JsonIOException, JsonSyntaxException {
try { try {
JsonReader jsonReader = new JsonReader(json); JsonReader jsonReader = new JsonReader(reader);
JsonElement element = parse(jsonReader); JsonElement element = parseReader(jsonReader);
if (!element.isJsonNull() && jsonReader.peek() != JsonToken.END_DOCUMENT) { if (!element.isJsonNull() && jsonReader.peek() != JsonToken.END_DOCUMENT) {
throw new JsonSyntaxException("Did not consume the entire document."); throw new JsonSyntaxException("Did not consume the entire document.");
} }
@ -75,19 +76,37 @@ public final class JsonParser {
* *
* @throws JsonParseException if there is an IOException or if the specified * @throws JsonParseException if there is an IOException or if the specified
* text is not valid JSON * text is not valid JSON
* @since 1.6
*/ */
public JsonElement parse(JsonReader json) throws JsonIOException, JsonSyntaxException { public static JsonElement parseReader(JsonReader reader)
boolean lenient = json.isLenient(); throws JsonIOException, JsonSyntaxException {
json.setLenient(true); boolean lenient = reader.isLenient();
reader.setLenient(true);
try { try {
return Streams.parse(json); return Streams.parse(reader);
} catch (StackOverflowError e) { } catch (StackOverflowError e) {
throw new JsonParseException("Failed parsing JSON source: " + json + " to Json", e); throw new JsonParseException("Failed parsing JSON source: " + reader + " to Json", e);
} catch (OutOfMemoryError e) { } catch (OutOfMemoryError e) {
throw new JsonParseException("Failed parsing JSON source: " + json + " to Json", e); throw new JsonParseException("Failed parsing JSON source: " + reader + " to Json", e);
} finally { } finally {
json.setLenient(lenient); reader.setLenient(lenient);
} }
} }
/** @deprecated Use {@link JsonParser#parseString} */
@Deprecated
public JsonElement parse(String json) throws JsonSyntaxException {
return parseString(json);
}
/** @deprecated Use {@link JsonParser#parseReader(Reader)} */
@Deprecated
public JsonElement parse(Reader json) throws JsonIOException, JsonSyntaxException {
return parseReader(json);
}
/** @deprecated Use {@link JsonParser#parseReader(JsonReader)} */
@Deprecated
public JsonElement parse(JsonReader json) throws JsonIOException, JsonSyntaxException {
return parseReader(json);
}
} }

View File

@ -128,7 +128,7 @@ public class JsonObjectTest extends TestCase {
} }
public void testReadPropertyWithEmptyStringName() { public void testReadPropertyWithEmptyStringName() {
JsonObject jsonObj = new JsonParser().parse("{\"\":true}").getAsJsonObject(); JsonObject jsonObj = JsonParser.parseString("{\"\":true}").getAsJsonObject();
assertEquals(true, jsonObj.get("").getAsBoolean()); assertEquals(true, jsonObj.get("").getAsBoolean());
} }

View File

@ -32,23 +32,16 @@ import com.google.gson.stream.JsonReader;
* @author Inderjeet Singh * @author Inderjeet Singh
*/ */
public class JsonParserTest extends TestCase { public class JsonParserTest extends TestCase {
private JsonParser parser;
@Override
protected void setUp() throws Exception {
super.setUp();
parser = new JsonParser();
}
public void testParseInvalidJson() { public void testParseInvalidJson() {
try { try {
parser.parse("[[]"); JsonParser.parseString("[[]");
fail(); fail();
} catch (JsonSyntaxException expected) { } } catch (JsonSyntaxException expected) { }
} }
public void testParseUnquotedStringArrayFails() { public void testParseUnquotedStringArrayFails() {
JsonElement element = parser.parse("[a,b,c]"); JsonElement element = JsonParser.parseString("[a,b,c]");
assertEquals("a", element.getAsJsonArray().get(0).getAsString()); assertEquals("a", element.getAsJsonArray().get(0).getAsString());
assertEquals("b", element.getAsJsonArray().get(1).getAsString()); assertEquals("b", element.getAsJsonArray().get(1).getAsString());
assertEquals("c", element.getAsJsonArray().get(2).getAsString()); assertEquals("c", element.getAsJsonArray().get(2).getAsString());
@ -57,38 +50,38 @@ public class JsonParserTest extends TestCase {
public void testParseString() { public void testParseString() {
String json = "{a:10,b:'c'}"; String json = "{a:10,b:'c'}";
JsonElement e = parser.parse(json); JsonElement e = JsonParser.parseString(json);
assertTrue(e.isJsonObject()); assertTrue(e.isJsonObject());
assertEquals(10, e.getAsJsonObject().get("a").getAsInt()); assertEquals(10, e.getAsJsonObject().get("a").getAsInt());
assertEquals("c", e.getAsJsonObject().get("b").getAsString()); assertEquals("c", e.getAsJsonObject().get("b").getAsString());
} }
public void testParseEmptyString() { public void testParseEmptyString() {
JsonElement e = parser.parse("\" \""); JsonElement e = JsonParser.parseString("\" \"");
assertTrue(e.isJsonPrimitive()); assertTrue(e.isJsonPrimitive());
assertEquals(" ", e.getAsString()); assertEquals(" ", e.getAsString());
} }
public void testParseEmptyWhitespaceInput() { public void testParseEmptyWhitespaceInput() {
JsonElement e = parser.parse(" "); JsonElement e = JsonParser.parseString(" ");
assertTrue(e.isJsonNull()); assertTrue(e.isJsonNull());
} }
public void testParseUnquotedSingleWordStringFails() { public void testParseUnquotedSingleWordStringFails() {
assertEquals("Test", parser.parse("Test").getAsString()); assertEquals("Test", JsonParser.parseString("Test").getAsString());
} }
public void testParseUnquotedMultiWordStringFails() { public void testParseUnquotedMultiWordStringFails() {
String unquotedSentence = "Test is a test..blah blah"; String unquotedSentence = "Test is a test..blah blah";
try { try {
parser.parse(unquotedSentence); JsonParser.parseString(unquotedSentence);
fail(); fail();
} catch (JsonSyntaxException expected) { } } catch (JsonSyntaxException expected) { }
} }
public void testParseMixedArray() { public void testParseMixedArray() {
String json = "[{},13,\"stringValue\"]"; String json = "[{},13,\"stringValue\"]";
JsonElement e = parser.parse(json); JsonElement e = JsonParser.parseString(json);
assertTrue(e.isJsonArray()); assertTrue(e.isJsonArray());
JsonArray array = e.getAsJsonArray(); JsonArray array = e.getAsJsonArray();
@ -99,7 +92,7 @@ public class JsonParserTest extends TestCase {
public void testParseReader() { public void testParseReader() {
StringReader reader = new StringReader("{a:10,b:'c'}"); StringReader reader = new StringReader("{a:10,b:'c'}");
JsonElement e = parser.parse(reader); JsonElement e = JsonParser.parseReader(reader);
assertTrue(e.isJsonObject()); assertTrue(e.isJsonObject());
assertEquals(10, e.getAsJsonObject().get("a").getAsInt()); assertEquals(10, e.getAsJsonObject().get("a").getAsInt());
assertEquals("c", e.getAsJsonObject().get("b").getAsString()); assertEquals("c", e.getAsJsonObject().get("b").getAsString());

View File

@ -112,7 +112,7 @@ public class JsonParserTest extends TestCase {
public void testChangingCustomTreeAndDeserializing() { public void testChangingCustomTreeAndDeserializing() {
StringReader json = StringReader json =
new StringReader("{'stringValue':'no message','intValue':10,'longValue':20}"); new StringReader("{'stringValue':'no message','intValue':10,'longValue':20}");
JsonObject obj = (JsonObject) new JsonParser().parse(json); JsonObject obj = (JsonObject) JsonParser.parseReader(json);
obj.remove("stringValue"); obj.remove("stringValue");
obj.addProperty("stringValue", "fooBar"); obj.addProperty("stringValue", "fooBar");
BagOfPrimitives target = gson.fromJson(obj, BagOfPrimitives.class); BagOfPrimitives target = gson.fromJson(obj, BagOfPrimitives.class);

View File

@ -608,7 +608,7 @@ public class MapTest extends TestCase {
String json = "{'2.3':'a'}"; String json = "{'2.3':'a'}";
Map<Double, String> map = new LinkedHashMap<Double, String>(); Map<Double, String> map = new LinkedHashMap<Double, String>();
map.put(2.3, "a"); map.put(2.3, "a");
JsonElement tree = new JsonParser().parse(json); JsonElement tree = JsonParser.parseString(json);
assertEquals(map, gson.fromJson(tree, new TypeToken<Map<Double, String>>() {}.getType())); assertEquals(map, gson.fromJson(tree, new TypeToken<Map<Double, String>>() {}.getType()));
} }

View File

@ -26,7 +26,7 @@ import junit.framework.TestCase;
public final class JsonElementReaderTest extends TestCase { public final class JsonElementReaderTest extends TestCase {
public void testNumbers() throws IOException { public void testNumbers() throws IOException {
JsonElement element = new JsonParser().parse("[1, 2, 3]"); JsonElement element = JsonParser.parseString("[1, 2, 3]");
JsonTreeReader reader = new JsonTreeReader(element); JsonTreeReader reader = new JsonTreeReader(element);
reader.beginArray(); reader.beginArray();
assertEquals(1, reader.nextInt()); assertEquals(1, reader.nextInt());
@ -36,7 +36,7 @@ public final class JsonElementReaderTest extends TestCase {
} }
public void testLenientNansAndInfinities() throws IOException { public void testLenientNansAndInfinities() throws IOException {
JsonElement element = new JsonParser().parse("[NaN, -Infinity, Infinity]"); JsonElement element = JsonParser.parseString("[NaN, -Infinity, Infinity]");
JsonTreeReader reader = new JsonTreeReader(element); JsonTreeReader reader = new JsonTreeReader(element);
reader.setLenient(true); reader.setLenient(true);
reader.beginArray(); reader.beginArray();
@ -47,7 +47,7 @@ public final class JsonElementReaderTest extends TestCase {
} }
public void testStrictNansAndInfinities() throws IOException { public void testStrictNansAndInfinities() throws IOException {
JsonElement element = new JsonParser().parse("[NaN, -Infinity, Infinity]"); JsonElement element = JsonParser.parseString("[NaN, -Infinity, Infinity]");
JsonTreeReader reader = new JsonTreeReader(element); JsonTreeReader reader = new JsonTreeReader(element);
reader.setLenient(false); reader.setLenient(false);
reader.beginArray(); reader.beginArray();
@ -73,7 +73,7 @@ public final class JsonElementReaderTest extends TestCase {
} }
public void testNumbersFromStrings() throws IOException { public void testNumbersFromStrings() throws IOException {
JsonElement element = new JsonParser().parse("[\"1\", \"2\", \"3\"]"); JsonElement element = JsonParser.parseString("[\"1\", \"2\", \"3\"]");
JsonTreeReader reader = new JsonTreeReader(element); JsonTreeReader reader = new JsonTreeReader(element);
reader.beginArray(); reader.beginArray();
assertEquals(1, reader.nextInt()); assertEquals(1, reader.nextInt());
@ -83,7 +83,7 @@ public final class JsonElementReaderTest extends TestCase {
} }
public void testStringsFromNumbers() throws IOException { public void testStringsFromNumbers() throws IOException {
JsonElement element = new JsonParser().parse("[1]"); JsonElement element = JsonParser.parseString("[1]");
JsonTreeReader reader = new JsonTreeReader(element); JsonTreeReader reader = new JsonTreeReader(element);
reader.beginArray(); reader.beginArray();
assertEquals("1", reader.nextString()); assertEquals("1", reader.nextString());
@ -91,7 +91,7 @@ public final class JsonElementReaderTest extends TestCase {
} }
public void testBooleans() throws IOException { public void testBooleans() throws IOException {
JsonElement element = new JsonParser().parse("[true, false]"); JsonElement element = JsonParser.parseString("[true, false]");
JsonTreeReader reader = new JsonTreeReader(element); JsonTreeReader reader = new JsonTreeReader(element);
reader.beginArray(); reader.beginArray();
assertEquals(true, reader.nextBoolean()); assertEquals(true, reader.nextBoolean());
@ -100,7 +100,7 @@ public final class JsonElementReaderTest extends TestCase {
} }
public void testNulls() throws IOException { public void testNulls() throws IOException {
JsonElement element = new JsonParser().parse("[null,null]"); JsonElement element = JsonParser.parseString("[null,null]");
JsonTreeReader reader = new JsonTreeReader(element); JsonTreeReader reader = new JsonTreeReader(element);
reader.beginArray(); reader.beginArray();
reader.nextNull(); reader.nextNull();
@ -109,7 +109,7 @@ public final class JsonElementReaderTest extends TestCase {
} }
public void testStrings() throws IOException { public void testStrings() throws IOException {
JsonElement element = new JsonParser().parse("[\"A\",\"B\"]"); JsonElement element = JsonParser.parseString("[\"A\",\"B\"]");
JsonTreeReader reader = new JsonTreeReader(element); JsonTreeReader reader = new JsonTreeReader(element);
reader.beginArray(); reader.beginArray();
assertEquals("A", reader.nextString()); assertEquals("A", reader.nextString());
@ -118,7 +118,7 @@ public final class JsonElementReaderTest extends TestCase {
} }
public void testArray() throws IOException { public void testArray() throws IOException {
JsonElement element = new JsonParser().parse("[1, 2, 3]"); JsonElement element = JsonParser.parseString("[1, 2, 3]");
JsonTreeReader reader = new JsonTreeReader(element); JsonTreeReader reader = new JsonTreeReader(element);
assertEquals(JsonToken.BEGIN_ARRAY, reader.peek()); assertEquals(JsonToken.BEGIN_ARRAY, reader.peek());
reader.beginArray(); reader.beginArray();
@ -134,7 +134,7 @@ public final class JsonElementReaderTest extends TestCase {
} }
public void testObject() throws IOException { public void testObject() throws IOException {
JsonElement element = new JsonParser().parse("{\"A\": 1, \"B\": 2}"); JsonElement element = JsonParser.parseString("{\"A\": 1, \"B\": 2}");
JsonTreeReader reader = new JsonTreeReader(element); JsonTreeReader reader = new JsonTreeReader(element);
assertEquals(JsonToken.BEGIN_OBJECT, reader.peek()); assertEquals(JsonToken.BEGIN_OBJECT, reader.peek());
reader.beginObject(); reader.beginObject();
@ -152,14 +152,14 @@ public final class JsonElementReaderTest extends TestCase {
} }
public void testEmptyArray() throws IOException { public void testEmptyArray() throws IOException {
JsonElement element = new JsonParser().parse("[]"); JsonElement element = JsonParser.parseString("[]");
JsonTreeReader reader = new JsonTreeReader(element); JsonTreeReader reader = new JsonTreeReader(element);
reader.beginArray(); reader.beginArray();
reader.endArray(); reader.endArray();
} }
public void testNestedArrays() throws IOException { public void testNestedArrays() throws IOException {
JsonElement element = new JsonParser().parse("[[],[[]]]"); JsonElement element = JsonParser.parseString("[[],[[]]]");
JsonTreeReader reader = new JsonTreeReader(element); JsonTreeReader reader = new JsonTreeReader(element);
reader.beginArray(); reader.beginArray();
reader.beginArray(); reader.beginArray();
@ -172,7 +172,7 @@ public final class JsonElementReaderTest extends TestCase {
} }
public void testNestedObjects() throws IOException { public void testNestedObjects() throws IOException {
JsonElement element = new JsonParser().parse("{\"A\":{},\"B\":{\"C\":{}}}"); JsonElement element = JsonParser.parseString("{\"A\":{},\"B\":{\"C\":{}}}");
JsonTreeReader reader = new JsonTreeReader(element); JsonTreeReader reader = new JsonTreeReader(element);
reader.beginObject(); reader.beginObject();
assertEquals("A", reader.nextName()); assertEquals("A", reader.nextName());
@ -188,14 +188,14 @@ public final class JsonElementReaderTest extends TestCase {
} }
public void testEmptyObject() throws IOException { public void testEmptyObject() throws IOException {
JsonElement element = new JsonParser().parse("{}"); JsonElement element = JsonParser.parseString("{}");
JsonTreeReader reader = new JsonTreeReader(element); JsonTreeReader reader = new JsonTreeReader(element);
reader.beginObject(); reader.beginObject();
reader.endObject(); reader.endObject();
} }
public void testSkipValue() throws IOException { public void testSkipValue() throws IOException {
JsonElement element = new JsonParser().parse("[\"A\",{\"B\":[[]]},\"C\",[[]],\"D\",null]"); JsonElement element = JsonParser.parseString("[\"A\",{\"B\":[[]]},\"C\",[[]],\"D\",null]");
JsonTreeReader reader = new JsonTreeReader(element); JsonTreeReader reader = new JsonTreeReader(element);
reader.beginArray(); reader.beginArray();
assertEquals("A", reader.nextString()); assertEquals("A", reader.nextString());
@ -208,7 +208,7 @@ public final class JsonElementReaderTest extends TestCase {
} }
public void testWrongType() throws IOException { public void testWrongType() throws IOException {
JsonElement element = new JsonParser().parse("[[],\"A\"]"); JsonElement element = JsonParser.parseString("[[],\"A\"]");
JsonTreeReader reader = new JsonTreeReader(element); JsonTreeReader reader = new JsonTreeReader(element);
reader.beginArray(); reader.beginArray();
try { try {
@ -299,7 +299,7 @@ public final class JsonElementReaderTest extends TestCase {
} }
public void testEarlyClose() throws IOException { public void testEarlyClose() throws IOException {
JsonElement element = new JsonParser().parse("[1, 2, 3]"); JsonElement element = JsonParser.parseString("[1, 2, 3]");
JsonTreeReader reader = new JsonTreeReader(element); JsonTreeReader reader = new JsonTreeReader(element);
reader.beginArray(); reader.beginArray();
reader.close(); reader.close();