ObjectMapper
各个方法的示例:
1. readTree(String json)
该方法将 JSON 字符串解析为 JsonNode
对象。这允许你以树形结构来访问 JSON 数据。
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper;
public class Example { public static void main(String[] args) throws Exception { String jsonString = "{\"name\": \"John\", \"age\": 30}";
ObjectMapper objectMapper = new ObjectMapper(); JsonNode rootNode = objectMapper.readTree(jsonString);
String name = rootNode.get("name").asText(); int age = rootNode.get("age").asInt();
System.out.println("Name: " + name); System.out.println("Age: " + age); } }
|
输出:
2. writeValueAsString(Object value)
该方法将 Java 对象转换为 JSON 字符串。
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| import com.fasterxml.jackson.databind.ObjectMapper;
public class Example { public static void main(String[] args) throws Exception { Person person = new Person("John", 30);
ObjectMapper objectMapper = new ObjectMapper(); String jsonString = objectMapper.writeValueAsString(person);
System.out.println(jsonString); } }
class Person { private String name; private int age;
public Person() {} public Person(String name, int age) { this.name = name; this.age = age; } 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; } }
|
输出:
1
| {"name":"John","age":30}
|
3. readValue(String json, Class<T> valueType)
该方法将 JSON 字符串转换为指定类型的 Java 对象。
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| import com.fasterxml.jackson.databind.ObjectMapper;
public class Example { public static void main(String[] args) throws Exception { String jsonString = "{\"name\": \"John\", \"age\": 30}";
ObjectMapper objectMapper = new ObjectMapper(); Person person = objectMapper.readValue(jsonString, Person.class);
System.out.println("Name: " + person.getName()); System.out.println("Age: " + person.getAge()); } }
class Person { private String name; private int age;
public Person() {} public Person(String name, int age) { this.name = name; this.age = age; } 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
如何处理 JSON 数据的常见操作,包括解析 JSON、序列化对象和将 JSON 转换为 Java 对象。