Read the next element of the JSON input stream as a number. @return Number object @throws JsonException if the next element isn't a number @throws UncheckedIOException if an I/O exception is encountered
()
| 222 | * @throws UncheckedIOException if an I/O exception is encountered |
| 223 | */ |
| 224 | public Number nextNumber() { |
| 225 | expect(JsonType.NUMBER); |
| 226 | boolean mightBeDecimal = false; |
| 227 | StringBuilder builder = new StringBuilder(); |
| 228 | // We know it's safe to use a do/while loop since the first character was a number |
| 229 | boolean read = true; |
| 230 | do { |
| 231 | switch (input.peek()) { |
| 232 | case '-': |
| 233 | case '+': |
| 234 | case '0': |
| 235 | case '1': |
| 236 | case '2': |
| 237 | case '3': |
| 238 | case '4': |
| 239 | case '5': |
| 240 | case '6': |
| 241 | case '7': |
| 242 | case '8': |
| 243 | case '9': |
| 244 | builder.append(input.read()); |
| 245 | break; |
| 246 | case '.': |
| 247 | case 'e': |
| 248 | case 'E': |
| 249 | mightBeDecimal = true; |
| 250 | builder.append(input.read()); |
| 251 | break; |
| 252 | default: |
| 253 | read = false; |
| 254 | } |
| 255 | } while (read); |
| 256 | |
| 257 | try { |
| 258 | // The JSON Schema does state the decimal point should not be used distinguish between |
| 259 | // integers and floating point values. |
| 260 | // Therefore, using a Long is only a fast path here, but we should not rely on the `double` |
| 261 | // value below is a real floating point. |
| 262 | if (!mightBeDecimal) { |
| 263 | return Long.valueOf(builder.toString()); |
| 264 | } |
| 265 | |
| 266 | return new BigDecimal(builder.toString()).doubleValue(); |
| 267 | } catch (NumberFormatException e) { |
| 268 | throw new JsonException("Unable to parse to a number: " + builder + ". " + input, e); |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | /** |
| 273 | * Read the next element of the JSON input stream as a string. |