Skip to content

Commit 8a51b95

Browse files
authored
[java] fix JSON parsing of numbers with exponent (#16961)
1 parent 32d7748 commit 8a51b95

File tree

2 files changed

+34
-18
lines changed

2 files changed

+34
-18
lines changed

java/src/org/openqa/selenium/json/JsonInput.java

Lines changed: 30 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -220,31 +220,43 @@ public String nextName() {
220220
*/
221221
public Number nextNumber() {
222222
expect(JsonType.NUMBER);
223+
boolean decimal = false;
223224
StringBuilder builder = new StringBuilder();
224225
// We know it's safe to use a do/while loop since the first character was a number
225-
boolean fractionalPart = false;
226+
boolean read = true;
226227
do {
227-
char read = input.peek();
228-
if (Character.isDigit(read)
229-
|| read == '+'
230-
|| read == '-'
231-
|| read == 'e'
232-
|| read == 'E'
233-
|| read == '.') {
234-
builder.append(input.read());
235-
} else {
236-
break;
228+
switch (input.peek()) {
229+
case '-':
230+
case '+':
231+
case '0':
232+
case '1':
233+
case '2':
234+
case '3':
235+
case '4':
236+
case '5':
237+
case '6':
238+
case '7':
239+
case '8':
240+
case '9':
241+
builder.append(input.read());
242+
break;
243+
case '.':
244+
case 'e':
245+
case 'E':
246+
decimal = true;
247+
builder.append(input.read());
248+
break;
249+
default:
250+
read = false;
237251
}
238-
239-
fractionalPart |= (read == '.');
240-
} while (true);
252+
} while (read);
241253

242254
try {
243-
Number number = new BigDecimal(builder.toString());
244-
if (fractionalPart) {
245-
return number.doubleValue();
255+
if (!decimal) {
256+
return Long.valueOf(builder.toString());
246257
}
247-
return number.longValue();
258+
259+
return new BigDecimal(builder.toString()).doubleValue();
248260
} catch (NumberFormatException e) {
249261
throw new JsonException("Unable to parse to a number: " + builder + ". " + input);
250262
}

java/test/org/openqa/selenium/json/JsonTest.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,10 @@ void canReadANumber() {
6363
assertThat((Number) new Json().toType("42", Number.class)).isEqualTo(42L);
6464
assertThat((Integer) new Json().toType("42", Integer.class)).isEqualTo(42);
6565
assertThat((Double) new Json().toType("42", Double.class)).isEqualTo(42.0);
66+
assertThat((Double) new Json().toType("4.2e+1", Double.class)).isEqualTo(42.0);
67+
assertThat((Double) new Json().toType("42e+1", Double.class)).isEqualTo(420.0);
68+
assertThat((Double) new Json().toType("42e-1", Double.class)).isEqualTo(4.2);
69+
assertThat((Double) new Json().toType("4.2e-1", Double.class)).isEqualTo(0.42);
6670
}
6771

6872
@Test

0 commit comments

Comments
 (0)