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()) {
168
168
return Enum .valueOf ((Class <Enum >) javaType , value .toString ());
169
169
}
170
170
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 ;
173
187
}
174
188
175
189
}
Original file line number Diff line number Diff line change 16
16
17
17
package org .springframework .ai .util .json ;
18
18
19
- import java .lang .reflect .Type ;
20
-
21
19
import com .fasterxml .jackson .core .type .TypeReference ;
22
20
import org .junit .jupiter .api .Test ;
23
21
22
+ import java .lang .reflect .Type ;
23
+
24
24
import static org .assertj .core .api .Assertions .assertThat ;
25
25
import static org .assertj .core .api .Assertions .assertThatThrownBy ;
26
26
@@ -241,6 +241,22 @@ var record = new TestRecord("John", 30);
241
241
assertThat (value ).isEqualTo (new TestRecord ("John" , 30 ));
242
242
}
243
243
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
+
244
260
@ Test
245
261
void fromScientificNotationToInteger () {
246
262
var value = JsonParser .toTypedObject ("1.5E7" , Integer .class );
@@ -265,6 +281,14 @@ void doesNotDoubleSerializeValidJsonString() {
265
281
record TestRecord (String name , Integer age ) {
266
282
}
267
283
284
+ static class TestSimpleObject {
285
+
286
+ public String name ;
287
+
288
+ public int age ;
289
+
290
+ }
291
+
268
292
enum TestEnum {
269
293
270
294
VALUE
You can’t perform that action at this time.
0 commit comments