Skip to content

Commit 0715af2

Browse files
authored
feat: Eliminate one deserialization step in the majority of scenarios when parsing Model response (#4003)
Fixes #4003 Auto-cherry-pick to 1.0.x Signed-off-by: bourne7 <[email protected]>
1 parent f7e6b34 commit 0715af2

File tree

2 files changed

+42
-4
lines changed

2 files changed

+42
-4
lines changed

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

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -168,8 +168,22 @@ else if (javaType.isEnum()) {
168168
return Enum.valueOf((Class<Enum>) javaType, value.toString());
169169
}
170170

171-
String json = JsonParser.toJson(value);
172-
return JsonParser.fromJson(json, javaType);
171+
Object result = null;
172+
if (value instanceof String jsonString) {
173+
try {
174+
result = JsonParser.fromJson(jsonString, javaType);
175+
}
176+
catch (Exception e) {
177+
// ignore
178+
}
179+
}
180+
181+
if (result == null) {
182+
String json = JsonParser.toJson(value);
183+
result = JsonParser.fromJson(json, javaType);
184+
}
185+
186+
return result;
173187
}
174188

175189
}

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

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,11 @@
1616

1717
package org.springframework.ai.util.json;
1818

19-
import java.lang.reflect.Type;
20-
2119
import com.fasterxml.jackson.core.type.TypeReference;
2220
import org.junit.jupiter.api.Test;
2321

22+
import java.lang.reflect.Type;
23+
2424
import static org.assertj.core.api.Assertions.assertThat;
2525
import static org.assertj.core.api.Assertions.assertThatThrownBy;
2626

@@ -241,6 +241,22 @@ var record = new TestRecord("John", 30);
241241
assertThat(value).isEqualTo(new TestRecord("John", 30));
242242
}
243243

244+
@Test
245+
void fromStringToObject() {
246+
String jsonString = """
247+
{
248+
"name": "foo",
249+
"age": 7
250+
}
251+
""";
252+
var value = JsonParser.toTypedObject(jsonString, TestSimpleObject.class);
253+
assertThat(value).isOfAnyClassIn(TestSimpleObject.class);
254+
255+
TestSimpleObject testSimpleObject = (TestSimpleObject) value;
256+
assertThat(testSimpleObject.name).isEqualTo("foo");
257+
assertThat(testSimpleObject.age).isEqualTo(7);
258+
}
259+
244260
@Test
245261
void fromScientificNotationToInteger() {
246262
var value = JsonParser.toTypedObject("1.5E7", Integer.class);
@@ -265,6 +281,14 @@ void doesNotDoubleSerializeValidJsonString() {
265281
record TestRecord(String name, Integer age) {
266282
}
267283

284+
static class TestSimpleObject {
285+
286+
public String name;
287+
288+
public int age;
289+
290+
}
291+
268292
enum TestEnum {
269293

270294
VALUE

0 commit comments

Comments
 (0)