Make the nextJsonElement more robust

Add test cases
This commit is contained in:
Simon Guerout 2021-08-25 09:56:01 -04:00 committed by Éamonn McManus
parent 62a9702385
commit ac14b4c197
2 changed files with 44 additions and 2 deletions

View File

@ -250,8 +250,14 @@ public final class JsonTreeReader extends JsonReader {
}
JsonElement nextJsonElement() throws IOException {
if (peek() == JsonToken.NAME) {
throw new IllegalStateException("Can't turn a name into a JsonElement");
final JsonToken peeked = peek();
if (
peeked == JsonToken.NAME
|| peeked == JsonToken.END_ARRAY
|| peeked == JsonToken.END_OBJECT
|| peeked == JsonToken.END_DOCUMENT
) {
throw new IllegalStateException("Unexpected " + peeked + " when reading a JsonElement.");
}
final JsonElement element = (JsonElement) peekStack();
skipValue();

View File

@ -18,6 +18,7 @@ package com.google.gson.internal.bind;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.google.gson.stream.JsonToken;
import java.io.IOException;
import junit.framework.TestCase;
@ -298,6 +299,41 @@ public final class JsonElementReaderTest extends TestCase {
reader.endArray();
}
public void testNextJsonElement() throws IOException {
final JsonElement element = JsonParser.parseString("{\"A\": 1, \"B\" : {}, \"C\" : []}");
JsonTreeReader reader = new JsonTreeReader(element);
reader.beginObject();
try {
reader.nextJsonElement();
fail();
} catch (IllegalStateException expected) {
}
reader.nextName();
assertEquals(reader.nextJsonElement(), new JsonPrimitive(1));
reader.nextName();
reader.beginObject();
try {
reader.nextJsonElement();
fail();
} catch (IllegalStateException expected) {
}
reader.endObject();
reader.nextName();
reader.beginArray();
try {
reader.nextJsonElement();
fail();
} catch (IllegalStateException expected) {
}
reader.endArray();
reader.endObject();
try {
reader.nextJsonElement();
fail();
} catch (IllegalStateException expected) {
}
}
public void testEarlyClose() throws IOException {
JsonElement element = JsonParser.parseString("[1, 2, 3]");
JsonTreeReader reader = new JsonTreeReader(element);