Java jackson 将ObjectNode 转换为对象
要将 Jackson 的 ObjectNode 转换为对象,可以使用 Jackson 的 ObjectMapper 类的 convertValue 方法。以下是一个示例代码:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main {
public static void main(String[] args) {
// 创建 ObjectMapper 对象
ObjectMapper objectMapper = new ObjectMapper();
// 创建一个 ObjectNode 对象
ObjectNode objectNode = objectMapper.createObjectNode();
objectNode.put("name", "John");
objectNode.put("age", 30);
// 将 ObjectNode 转换为对象
Person person = objectMapper.convertValue(objectNode, Person.class);
// 打印转换后的对象
System.out.println(person.getName()); // 输出 "John"
System.out.println(person.getAge()); // 输出 30
}
}
class Person {
private String name;
private int age;
// 必须有一个无参构造函数
public Person() {}
// Getter 和 Setter 方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
在上面的示例中,我们首先创建了一个 ObjectMapper 对象,然后创建了一个 ObjectNode 对象并设置了一些属性。然后,我们使用 convertValue 方法将 ObjectNode 转换为 Person 对象。最后,我们打印了转换后的对象的属性值。
请注意,要成功转换为对象,Person 类必须具有与 ObjectNode 对象中的属性相匹配的属性和相应的 Getter 和 Setter 方法。此外,Person 类必须具有一个无参构造函数。
原文地址: https://www.cveoy.top/t/topic/iAJC 著作权归作者所有。请勿转载和采集!