一、jackson的maven依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>
二、实体类的建立
import com.fasterxml.jackson.annotation.JsonIgnore;
public class Person {
private Integer id;
private String name;
@JsonIgnore
private String hobbies;//兴趣爱好
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 String getHobbies() {
return hobbies;
}
public void setHobbies(String hobbies) {
this.hobbies = hobbies;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", hobbies=" + hobbies + "]";
}
}
三、测试类代码:
import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JSONTest {
public static void main(String[] args) throws IOException {
Person p = new Person();
p.setId(1001);
p.setName("huangbaokang");
p.setHobbies("篮球");
// 未加@JsonIgnore注解时,控制台打印输出{"id":1001,"name":"huangbaokang","hobbies":"篮球"}
// 加上@JsonIgnore注解时,控制台输出了{"id":1001,"name":"huangbaokang"},把hobbies的值过滤了。
System.out.println(new ObjectMapper().writeValueAsString(p));
}
}