要使用 ObjectMapper,首先需要将其添加到你的项目中。如果你使用 Maven,可以添加以下依赖到你的 pom.xml 文件中:
com.fasterxml.jackson.core
jackson-databind
你的版本号
然后,你可以使用 ObjectMapper 的实例来序列化和反序列化数据。
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonExample {
public static void main(String[] args) {
try {
ObjectMapper mapper = new ObjectMapper();
Person person = new Person();
person.setName("John Doe");
person.setAge(30);
String jsonString = mapper.writeValueAsString(person);
System.out.println(jsonString);
} catch (Exception e) {
e.printStackTrace();
}
}
static class Person {
private String name;
private int age;
// getters and setters
}
}
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonExample {
public static void main(String[] args) {
try {
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"name\":\"John Doe\",\"age\":30}";
Person person = mapper.readValue(jsonString, Person.class);
System.out.println(person.getName() + " is " + person.getAge() + " years old.");
} catch (Exception e) {
e.printStackTrace();
}
}
static class Person {
private String name;
private int age;
// getters and setters
}
}