Skip to content

Commit 69c081c

Browse files
BeomSeogKimilayaperumalg
authored andcommitted
fix(jsonparser): support scientific notation parsing for int/long
Fixes: #2995 Replaces direct parseInt/parseLong with BigDecimal-based parsing to handle scientific notation safely and accurately. Signed-off-by: BeomSeogKim <[email protected]>
1 parent f3b4624 commit 69c081c

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

spring-ai-model/src/main/java/org/springframework/ai/util/json/JsonParser.java

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package org.springframework.ai.util.json;
1818

1919
import java.lang.reflect.Type;
20+
import java.math.BigDecimal;
2021

2122
import com.fasterxml.jackson.core.JsonProcessingException;
2223
import com.fasterxml.jackson.core.type.TypeReference;
@@ -128,13 +129,15 @@ else if (javaType == Byte.class) {
128129
return Byte.parseByte(value.toString());
129130
}
130131
else if (javaType == Integer.class) {
131-
return Integer.parseInt(value.toString());
132+
BigDecimal bigDecimal = new BigDecimal(value.toString());
133+
return bigDecimal.intValueExact();
132134
}
133135
else if (javaType == Short.class) {
134136
return Short.parseShort(value.toString());
135137
}
136138
else if (javaType == Long.class) {
137-
return Long.parseLong(value.toString());
139+
BigDecimal bigDecimal = new BigDecimal(value.toString());
140+
return bigDecimal.longValueExact();
138141
}
139142
else if (javaType == Double.class) {
140143
return Double.parseDouble(value.toString());

spring-ai-model/src/test/java/org/springframework/ai/util/json/JsonParserTests.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,20 @@ var record = new TestRecord("John", 30);
241241
assertThat(value).isEqualTo(new TestRecord("John", 30));
242242
}
243243

244+
@Test
245+
void fromScientificNotationToInteger() {
246+
var value = JsonParser.toTypedObject("1.5E7", Integer.class);
247+
assertThat(value).isInstanceOf(Integer.class);
248+
assertThat(value).isEqualTo(15_000_000);
249+
}
250+
251+
@Test
252+
void fromScientificNotationToLong() {
253+
var value = JsonParser.toTypedObject("1.5E12", Long.class);
254+
assertThat(value).isInstanceOf(Long.class);
255+
assertThat(value).isEqualTo(1_500_000_000_000L);
256+
}
257+
244258
record TestRecord(String name, Integer age) {
245259
}
246260

0 commit comments

Comments
 (0)