Merge pull request #940 from square/jakew/skip-name-message/2019-09-26

Point at the offending name when failing on unknown
This commit is contained in:
Jesse Wilson
2019-09-26 21:56:49 -04:00
committed by GitHub
4 changed files with 23 additions and 3 deletions

View File

@@ -586,7 +586,10 @@ final class JsonUtf8Reader extends JsonReader {
@Override public void skipName() throws IOException {
if (failOnUnknown) {
throw new JsonDataException("Cannot skip unexpected " + peek() + " at " + getPath());
// Capture the peeked value before nextName() since it will reset its value.
Token peeked = peek();
nextName(); // Move the path forward onto the offending name.
throw new JsonDataException("Cannot skip unexpected " + peeked + " at " + getPath());
}
int p = peeked;
if (p == PEEKED_NONE) {

View File

@@ -167,7 +167,10 @@ final class JsonValueReader extends JsonReader {
@Override public void skipName() throws IOException {
if (failOnUnknown) {
throw new JsonDataException("Cannot skip unexpected " + peek() + " at " + getPath());
// Capture the peeked value before nextName() since it will reset its value.
Token peeked = peek();
nextName(); // Move the path forward onto the offending name.
throw new JsonDataException("Cannot skip unexpected " + peeked + " at " + getPath());
}
Map.Entry<?, ?> peeked = require(Map.Entry.class, Token.NAME);

View File

@@ -972,6 +972,20 @@ public final class JsonReaderTest {
reader.endObject();
}
@Test public void skipNameFailUnknown() throws IOException {
JsonReader reader = newReader("{\"a\":1,\"b\":2}");
reader.setFailOnUnknown(true);
reader.beginObject();
assertEquals("a", reader.nextName());
assertEquals(1, reader.nextInt());
try {
reader.skipName();
fail();
} catch (JsonDataException e) {
assertThat(e).hasMessage("Cannot skip unexpected NAME at $.b");
}
}
@Test public void skipNameOnValueFails() throws IOException {
JsonReader reader = newReader("1");
try {

View File

@@ -925,7 +925,7 @@ public final class MoshiTest {
adapter.fromJson("{\"diameter\":5,\"crust\":\"thick\",\"extraCheese\":true}");
fail();
} catch (JsonDataException expected) {
assertThat(expected).hasMessage("Cannot skip unexpected NAME at $.diameter");
assertThat(expected).hasMessage("Cannot skip unexpected NAME at $.crust");
}
}