项目中Jackson的常用用法

您所在的位置:网站首页 python中import用法 项目中Jackson的常用用法

项目中Jackson的常用用法

2023-03-24 01:56| 来源: 网络整理| 查看: 265

主要用在model对象输出渲染json的时候,我们可以通过相关注解控制输出结果,如日期格式,非空,敏感数据过滤等。如下使用springboot搭建的一个非常简单的工程。

package com.hbk.springbootmail.controller;import com.hbk.springbootmail.model.User;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.util.Date;@RestController@RequestMapping("/user")public class UserController {@GetMapping("/hello")public User hello(){User user = new User();user.setId(1);user.setBirthday(new Date());user.setName("huangbaokang");user.setPassword("123456");return user;}}

其中model对象,提供get和set方法

package com.hbk.springbootmail.model;import java.util.Date;public class User {private Integer id;private String name;private String password;private Date birthday;private String desc;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}public String getDesc() {return desc;}public void setDesc(String desc) {this.desc = desc;}}

浏览器访问localhost:8080/user/hello得到结果如下:

{"id":1,"name":"huangbaokang","password":"123456","birthday":"2020-01-20T06:21:51.396+0000","desc":null}

其中password为敏感字段,需要过滤,并且时间显示格式不对,desc为空输出来了。

设置如下注解,访问输出如下:

{"id":1,"name":"huangbaokang","birthday":"2020-01-20 02:31:40 下午"}

package com.hbk.springbootmail.model;import com.fasterxml.jackson.annotation.JsonFormat;import com.fasterxml.jackson.annotation.JsonIgnore;import com.fasterxml.jackson.annotation.JsonInclude;import com.fasterxml.jackson.annotation.JsonInclude.Include;import java.util.Date;public class User {private Integer id;private String name;@JsonIgnoreprivate String password;@JsonFormat(pattern="yyyy-MM-dd hh:mm:ss a",locale="zh",timezOne="GMT+8")private Date birthday;@JsonInclude(Include.NON_NULL)private String desc;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}public String getDesc() {return desc;}public void setDesc(String desc) {this.desc = desc;}}

这个知识点告诉我们,在联调接口的时候,在后端进行json格式转换设置其实还是挺方便的。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3