测试:创建实体类对象
public class User {
private Integer id;
private String name;
private Integer age;
private String sex;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + ", sex=" + sex + "]";
}
}
在pom文件中引入jar包
<properties>
<jackson.version>2.4.2</jackson.version>
</properties>
<!-- Jackson Json处理工具包 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
进行测试
package com.jt.test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jt.manage.pojo.User;
public class ObjectMapperTest {
//把对象转化为json串
@Test
public void objectToJSON() throws IOException {
User user=new User();
user.setId(10);
user.setName("测试");
user.setAge(1000);
user.setSex("男");
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(user);
System.out.println(json);
//将json串转换为对象
User user1 = objectMapper.readValue(json, User.class);
//get方法获取属性值 set方法为属性赋值
System.out.println(user);
}
/**
* 把list集合转化为JSON
* @throws IOException
*/
@Test
public void listToJSON() throws IOException {
List<User>userList=new ArrayList();
User user = new User();
user.setId(1);
user.setName("兔子");
user.setAge(3);
user.setSex("雄");
userList.add(user);
ObjectMapper objectMapper = new ObjectMapper();
String result = objectMapper.writeValueAsString(userList);
System.out.println(result);
//将JSON转换为list集合
@SuppressWarnings("unchecked")
List<User> uList = objectMapper.readValue(result, userList.getClass());
System.out.println(uList);
}
}