Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -168,8 +168,22 @@ else if (javaType.isEnum()) {
return Enum.valueOf((Class<Enum>) javaType, value.toString());
}

String json = JsonParser.toJson(value);
return JsonParser.fromJson(json, javaType);
Object result = null;
if (value instanceof String jsonString) {
try {
result = JsonParser.fromJson(jsonString, javaType);
}
catch (Exception e) {
// ignore
}
}

if (result == null) {
String json = JsonParser.toJson(value);
result = JsonParser.fromJson(json, javaType);
}

return result;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@

package org.springframework.ai.util.json;

import java.lang.reflect.Type;

import com.fasterxml.jackson.core.type.TypeReference;
import org.junit.jupiter.api.Test;

import java.lang.reflect.Type;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

Expand Down Expand Up @@ -241,6 +241,22 @@ var record = new TestRecord("John", 30);
assertThat(value).isEqualTo(new TestRecord("John", 30));
}

@Test
void fromStringToObject() {
String jsonString = """
{
"name": "foo",
"age": 7
}
""";
var value = JsonParser.toTypedObject(jsonString, TestSimpleObject.class);
assertThat(value).isOfAnyClassIn(TestSimpleObject.class);

TestSimpleObject testSimpleObject = (TestSimpleObject) value;
assertThat(testSimpleObject.name).isEqualTo("foo");
assertThat(testSimpleObject.age).isEqualTo(7);
}

@Test
void fromScientificNotationToInteger() {
var value = JsonParser.toTypedObject("1.5E7", Integer.class);
Expand All @@ -265,6 +281,14 @@ void doesNotDoubleSerializeValidJsonString() {
record TestRecord(String name, Integer age) {
}

static class TestSimpleObject {

public String name;

public int age;

}

enum TestEnum {

VALUE
Expand Down