File tree Expand file tree Collapse file tree 2 files changed +42
-4
lines changed
main/java/org/springframework/ai/util/json
test/java/org/springframework/ai/util/json Expand file tree Collapse file tree 2 files changed +42
-4
lines changed Original file line number Diff line number Diff 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}
Original file line number Diff line number Diff line change 1616
1717package org .springframework .ai .util .json ;
1818
19- import java .lang .reflect .Type ;
20-
2119import com .fasterxml .jackson .core .type .TypeReference ;
2220import org .junit .jupiter .api .Test ;
2321
22+ import java .lang .reflect .Type ;
23+
2424import static org .assertj .core .api .Assertions .assertThat ;
2525import 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
You can’t perform that action at this time.
0 commit comments