From 27bb9da18b8cb15ae9db03364131e38095b1c55a Mon Sep 17 00:00:00 2001 From: Janos Erdos Date: Wed, 13 Oct 2021 22:38:38 +0200 Subject: [PATCH] fix: negative numbers in json parser --- .../erdos/stencil/standalone/JsonParser.java | 4 ++-- .../stencil/standalone/JsonParserTest.java | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/java-src/io/github/erdos/stencil/standalone/JsonParser.java b/java-src/io/github/erdos/stencil/standalone/JsonParser.java index 53c8a983..e280f206 100644 --- a/java-src/io/github/erdos/stencil/standalone/JsonParser.java +++ b/java-src/io/github/erdos/stencil/standalone/JsonParser.java @@ -58,7 +58,7 @@ private static Object simpleParse(PushbackReader pb) throws IOException { } else if (c == 'n') { expectWord("null", pb); return null; - } else if (Character.isDigit(c)) { + } else if (Character.isDigit(c) || c == '+' || c == '-') { return readNumber(pb); } else { throw new IllegalStateException("Unexpected character: '" + c + "'"); @@ -69,7 +69,7 @@ static Number readNumber(PushbackReader pb) throws IOException { char[] arr = new char[128]; int len = pb.read(arr, 0, arr.length); - assert Character.isDigit(arr[0]); + assert arr[0] == '+' || arr[0] == '-' || Character.isDigit(arr[0]); int i = 0; while (i < len && (arr[i] == '.' || arr[i] == '-' || arr[i] == 'e' || Character.isDigit(arr[i]))) { diff --git a/java-test/io/github/erdos/stencil/standalone/JsonParserTest.java b/java-test/io/github/erdos/stencil/standalone/JsonParserTest.java index 66501023..b57d4349 100644 --- a/java-test/io/github/erdos/stencil/standalone/JsonParserTest.java +++ b/java-test/io/github/erdos/stencil/standalone/JsonParserTest.java @@ -107,6 +107,25 @@ public void readNumberTest2() throws IOException { assertEquals((Character) 'x', (Character) (char) pbr.read()); } + @Test + public void readNumberNegativeTest() throws IOException { + final String input = "-3"; + PushbackReader pbr = pbr(input); + + final Number result = JsonParser.readNumber(pbr); + assertEquals(new BigDecimal("-3"), result); + } + + @Test + @SuppressWarnings("unchecked") + public void readMapWithNegativeValue() throws IOException { + String input = "{\n" + " \"test\": -3\n" + "}"; + PushbackReader pbr = pbr(input); + + Map result = (Map) JsonParser.read(pbr); + assertEquals(new BigDecimal("-3"), result.get("test")); + } + @Test public void readScalarsTest() throws IOException { assertEquals(true, JsonParser.read(pbr("true")));