标签:time string 重用 timezone 实例 for etc get print
首先定义一个实例:
ObjectMapper mapper = new ObjectMapper();
定义一个Student类:
package jackson;
import java.util.Date;
public class Student {
private String name;
private int age;
private String position;
private Date createTime;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", position="
+ position + ", createTime=" + createTime + "]";
}
}
准备一个字符串:
String jsonString = "{\"name\":\"king\",\"age\":21}";
mapper.readValue(jsonString,Student.class);
System.out.println(student);
打印输出结果:
Student [name=king, age=21, position=null, createTime=null]
student.setCreateTime(new Date());
String json = mapper.writeValueAsString(student);
System.out.println(json);
打印输出结果:
{"name":"king","age":21,"position":null,"createTime":1524819355361}
两种方式:一种SimpleDateFormat,另外一种通过在属性字段注解
在Student.java属性字段createTime注解@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
import com.fasterxml.jackson.annotation.JsonFormat;
public class Student {
private String name;
private int age;
private String position;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
//省略get,set
}
打印输出结果:
{"name":"king","age":21,"position":null,"createTime":"2018-04-27 09:00:56"}
public class Student {
private String name;
private int age;
private String position;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
//省略get,set
}
打印输出结果:
{"name":"king","age":21,"position":null,"createTime":"2018-04-27 17:07:33"}
标签:time string 重用 timezone 实例 for etc get print
原文地址:https://www.cnblogs.com/30go/p/8963290.html