All of Jackson's operations are manipulated by Objectmapper object instances, and can be reused for this object instance.
First define an instance:
ObjectMapper mapper = new ObjectMapper();
Define a Student class:
Package Jackson; import java.util.Date; Public classStudent {PrivateString name;Private intAgePrivateString position;PrivateDate Createtime; PublicStringGetName() {returnName } Public void SetName(String name) { This.name= name; } Public int Getage() {returnAge } Public void Setage(intAge) { This. Age= age; } PublicStringgetPosition() {returnPosition } Public void SetPosition(String position) { This.position= position; } PublicDateGetcreatetime() {returnCreatetime; } Public void Setcreatetime(Date createtime) { This.Createtime= Createtime; }@Override PublicStringtoString() {return "Student [name="+ name +", age="+ Age +", position="+ Position +", createtime="+ Createtime +"]"; } }
Prepare a string:
String jsonString = "{\"name\":\"king\",\"age\":21}";
General operations: string-to-object
mapper.readValue(jsonString,Student.class); System.out.println(student);
Print out the results:
Student [name=king, age=21, position=null, createTime=null]
General operations: object to String
student.setCreateTime(new Date()); String json = mapper.writeValueAsString(student); System.out.println(json);
Print out the results:
{"name":"king","age":21,"position":null,"createTime":1524819355361}
How do I change the format of the Output date field?
Two ways: One SimpleDateFormat, the other by annotating in the attribute field
Createtime annotations in the Student.java attribute field@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
import com.fasterxml.jackson.annotation.JsonFormat;publicclass Student { private String name; privateint age; private String position; @JsonFormat"yyyy-MM-dd HH:mm:ss") private Date createTime; //省略get,set}
Print out the results:
{"name":"king","age":21,"position":null,"createTime":"2018-04-27 09:00:56"}
8-hour time difference problem: The above print results found, 8 hours less. Workaround: Increase the time zone on the annotations.
publicclass Student { private String name; privateint age; private String position; @JsonFormat"yyyy-MM-dd HH:mm:ss""GMT+8") private Date createTime; //省略get,set}
Print out the results:
{"name":"king","age":21,"position":null,"createTime":"2018-04-27 17:07:33"}
The use of "JSON" Jackson