我是靠谱客的博主 害羞皮卡丘,这篇文章主要介绍Java——jackson的注解@JsonProperty、@JsonIgnore、@JsonFormat、@JsonIgnoreProperties1.使用2.说明,现在分享给大家,希望可以做个参考。

1.使用

1.pom

复制代码
1
2
3
4
5
6
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.11.0</version> </dependency>

2.实体类 Student

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import java.io.Serializable; import java.util.Date; @Data @JsonIgnoreProperties(value = { "address", "score" }) public class Student implements Serializable { @JsonProperty(value = "sName", required = true) private String name; @JsonIgnore private int age; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GTM+8") private Date birthday; private String address; private String score; }

3.测试类

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class TestMain { public static void main(String[] args) throws JsonProcessingException { Student student = new Student(); student.setName("张三"); student.setAge(20); student.setBirthday(new Date()); student.setAddress("上海市"); student.setScore("90"); // 使用writeValuesAsString把对象转化成json字符串。 String stuJson = new ObjectMapper().writeValueAsString(student); System.out.println(stuJson); //使用readValue把字符串转化为对象 Student stu = new ObjectMapper().readValue(stuJson, Student.class); System.out.println(stu.toString()); System.out.println("=============================="); String json1 = "{"age":20,"birthday":"2022-04-18 09:38:47","address":"上海市","score":"90","sName":"张三"}"; Student stu1 = new ObjectMapper().readValue(json1, Student.class); System.out.println(stu1.toString()); } }

测试结果:

复制代码
1
2
3
4
5
{"birthday":"2022-04-18 09:42:58","sName":"张三"} Student(name=张三, age=0, birthday=Mon Apr 18 17:42:58 CST 2022, address=null, score=null) ============================== Student(name=张三, age=0, birthday=Mon Apr 18 17:38:47 CST 2022, address=null, score=null)

2.说明

@JsonProperty

value属性: 代表该属性序列化和反序列化的时候的key值。
required属性: 默认false,例如当required=true的时候,当反序列化的时候没有找到key值,就会报错。

@JsonIgnore

json序列化 会忽略这个字段
json反序列化,会忽略这个字段的赋值

@JsonFormat

json序列化,通过后面设置的格式进行数据的输出
json反序列化,通过设定的格式 进行数据的赋值

@JsonIgnoreProperties

类注解,
json序列化时,会忽略这些字段
json反序列化,会忽略这些字段的赋值

最后

以上就是害羞皮卡丘最近收集整理的关于Java——jackson的注解@JsonProperty、@JsonIgnore、@JsonFormat、@JsonIgnoreProperties1.使用2.说明的全部内容,更多相关Java——jackson内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(77)

评论列表共有 0 条评论

立即
投稿
返回
顶部