Let JsonValueReader.nextString read numbers. (#390)

* Let JsonValueReader.nextString read numbers.

This adds parity with JsonUtf8Reader and lets big number literals in JSON be read in as strings in Java.

* Remove trailing 0 in float literal.
This commit is contained in:
Eric Cochran 2017-11-24 04:23:12 -08:00 committed by Jesse Wilson
parent 03323ae998
commit f922371fa8
3 changed files with 39 additions and 3 deletions

View file

@ -152,9 +152,19 @@ final class JsonValueReader extends JsonReader {
}
@Override public String nextString() throws IOException {
String peeked = require(String.class, Token.STRING);
remove();
return peeked;
Object peeked = (stackSize != 0 ? stack[stackSize - 1] : null);
if (peeked instanceof String) {
remove();
return (String) peeked;
}
if (peeked instanceof Number) {
remove();
return peeked.toString();
}
if (peeked == JSON_READER_CLOSED) {
throw new IllegalStateException("JsonReader is closed");
}
throw typeMismatch(peeked, Token.STRING);
}
@Override public int selectString(Options options) throws IOException {

View file

@ -336,6 +336,18 @@ public final class JsonUtf8ReaderTest {
assertEquals("-0", reader.nextString());
}
@Test public void numberToStringCoersion() throws Exception {
JsonReader reader = newReader("[0, 9223372036854775807, 2.5, 3.010, \"a\", \"5\"]");
reader.beginArray();
assertThat(reader.nextString()).isEqualTo("0");
assertThat(reader.nextString()).isEqualTo("9223372036854775807");
assertThat(reader.nextString()).isEqualTo("2.5");
assertThat(reader.nextString()).isEqualTo("3.010");
assertThat(reader.nextString()).isEqualTo("a");
assertThat(reader.nextString()).isEqualTo("5");
reader.endArray();
}
@Test public void quotedNumberWithEscape() throws IOException {
JsonReader reader = newReader("[\"12\u00334\"]");
reader.setLenient(true);

View file

@ -17,6 +17,7 @@ package com.squareup.moshi;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
@ -423,6 +424,19 @@ public final class JsonValueReaderTest {
}
}
@Test public void numberToStringCoersion() throws Exception {
JsonReader reader =
new JsonValueReader(Arrays.asList(0, 9223372036854775807L, 2.5d, 3.01f, "a", "5"));
reader.beginArray();
assertThat(reader.nextString()).isEqualTo("0");
assertThat(reader.nextString()).isEqualTo("9223372036854775807");
assertThat(reader.nextString()).isEqualTo("2.5");
assertThat(reader.nextString()).isEqualTo("3.01");
assertThat(reader.nextString()).isEqualTo("a");
assertThat(reader.nextString()).isEqualTo("5");
reader.endArray();
}
@Test public void tooDeeplyNestedArrays() throws IOException {
Object root = Collections.emptyList();
for (int i = 0; i < 32; i++) {