Jackson所有的操作都是通过ObjectMapper对象实例来操作的,可以重用这个对象实例。
首先定义一个实例:
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"}
8小时时间差问题:上面打印结果发现,时间少8小时。
解决方法: 注解上增加时区。
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"}
其他的一些奇怪的配置
- 输出格式化,就是分行显示,该功能慎用:
打印输出样式mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
{ "name" : "king", "age" : 21, "position" : null, "createTime" : "2018-04-27 17:29:01" }
- 异常忽略
字符串转对象时,如果字符串中字段在对象中不存在,则忽略该字段@JsonIgnoreProperties(ignoreUnknown = true) 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 }
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编辑器真不会用)