我需要编写一些符合这些要求的Java代码:
Map<String, String>
形式接收。@JsonSetter
方法中不可用。)我已经部分工作了。 转换代码如下所示:
public class MyPojoConverter {
private final ObjectMapper objectMapper;
public MyPojoConverter(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
public MyPojo deserialize(Map<String, String> input) {
return objectMapper.convertValue(input, MyPojo.class);
}
}
此实现适用于
String
和枚举字段,但不适用于包含其他 POJO 的字段。 如果 MyPojo
有一个类型为 MyOtherPojo
的字段,我会收到如下错误:
java.lang.IllegalArgumentException: Cannot construct instance of `MyOtherPojo` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value (...
Jackson 似乎想要一个带有
MyOtherPojo
的 String
构造函数,但该类没有这样的构造函数,我无法向其中添加一个。 我希望 Jackson 自动递归地处理其他 POJO。 有没有办法让它做到这一点?
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;
import java.util.HashMap;
public class Main {
public static void main(String[] args) throws Exception {
// Example Map input
Map<String, String> inputMap = new HashMap<>();
inputMap.put("name", "John");
inputMap.put("gender", "MALE");
inputMap.put("address.street", "123 Elm St");
inputMap.put("address.city", "Gotham");
inputMap.put("contacts[0].type", "email");
inputMap.put("contacts[0].value", "[email protected]");
// Assuming ObjectMapper is injected or created here
ObjectMapper objectMapper = new ObjectMapper();
JsonConverter converter = new JsonConverter(objectMapper);
// Convert map to POJO
MainPojo pojo = converter.convertToPojo(inputMap);
// Print out the POJO
System.out.println("Name: " + pojo.getName());
System.out.println("Gender: " + pojo.getGender());
System.out.println("Street: " + pojo.getAddress().getStreet());
System.out.println("City: " + pojo.getAddress().getCity());
System.out.println("First Contact: " + pojo.getContacts().get(0).getValue`enter code here`());
}
}