首先定義一個實例:
ObjectMapper mapper = new ObjectMapper();
java
定義一個Student類:json
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}";
markdown
mapper.readValue(jsonString,Student.class); System.out.println(student);
打印輸出結果:app
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")
ide
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 }
打印輸出結果:this
{"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 }
打印輸出結果:code
{"name":"king","age":21,"position":null,"createTime":"2018-04-27 17:07:33"}
java mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
{ "name" : "king", "age" : 21, "position" : null, "createTime" : "2018-04-27 17:29:01" }
異常忽略
字符串轉對象時,若是字符串中字段在對象中不存在,則忽略該字段
````java
@JsonIgnoreProperties(ignoreUnknown = true)
public class Student {orm
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 }
````xml
3.其餘註解
@JsonIgnore
用來忽略某些字段,能夠用在Field或者Getter方法上,用在Setter方法時,和Filed效果同樣。
@JsonIgnoreProperties(ignoreUnknown = true)
將這個註解寫在類上以後,就會忽略類中不存在的字段
@JsonIgnoreProperties({ "internalId", "secretKey" })
將這個註解寫在類上以後,指定的字段不會被序列化和反序列化。
`objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE,true);` ***添加這個配置後,輸出時自動將類名做爲根元素。*** ````輸出以下: `{"Student":{"name":"king","age":21,"position":null,"createTime":"2018-05-02 10:06:29"}}` ```` `@JsonRootName("myPojo")` ***將這個註解寫在類上以後,根據指定的值生成根元素,做用相似於上面***
(博客園的這個markdown編輯器真不會用)