使用jackSON来实现JSON字符串和对象之间的转换
引入maven
<!--jackson-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
1、将JSON字符串转化成对象
public class JacksonTest {
public static void main(String[] args) {
//1.初始化JSON字符串
String json = "{\"name\":\"张小小\",\"age\":22,\"gender\":\"女\"}";
//2.创建ObjectMapper对象
ObjectMapper mapper = new ObjectMapper();
//3.转换为Java对象,Person对象
Person person = null;
try {
person = mapper.readValue(json, Person.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
System.out.println(person);
//Person [name=张小小, age=22, gender=女]
}
}
2、将对象转化成字符串
public class JacksonTest {
public static void main(String[] args) {
//1.获得对象信息
Person p = new Person("夏天","27","女");
//3.创建ObjectMapper对象
ObjectMapper mapper = new ObjectMapper();
String json = "";
//3.将对象转化成JSON字符串
try {
json = mapper.writeValueAsString(p);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
System.out.println(json);
}
}