大家好,又见面了,我是你们的朋友全栈君。
首先定义一个实例:
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"}输出格式化,就是分行显示,该功能:java mapper.configure(SerializationFeature.INDENT_OUTPUT, true); 打印输出样式{ "name" : "king", "age" : 21, "position" : null, "createTime" : "2018-04-27 17:29:01" }
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编辑器真不会用)
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/107556.html原文链接:https://javaforall.cn