Jackson学习(一) 美化/输出JSON


1、引入Maven依赖


com.fasterxml.jackson.core
jackson-databind
2.7.4


com.fasterxml.jackson.core
jackson-core
2.7.4


com.fasterxml.jackson.core
jackson-annotations
2.7.4

2、创建实体类

public class User {
private String userName;
private String passWord;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
private Integer type;

public User() {
}

public User(String userName, String passWord, Date createTime, Integer type) {
this.userName = userName;
this.passWord = passWord;
this.createTime = createTime;
this.type = type;
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getPassWord() {
return passWord;
}

public void setPassWord(String passWord) {
this.passWord = passWord;
}

public Date getCreateTime() {
return createTime;
}

public void setCreateTime(Date createTime) {
this.createTime = createTime;
}

public Integer getType() {
return type;
}

public void setType(Integer type) {
this.type = type;
}

3、创建Test

public class Test {
public static void main(String[] args) {
User user = new User();
user.setUserName("kosi");
user.setPassWord("123456");
user.setCreateTime(new Date());
user.setType(1);

ObjectMapper mapper = new ObjectMapper();
try {
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}

4、效果图