简介:介绍常用json框架和注解的使用,自定义返回json结构和格式
1、常用框架 阿里 fastjson,谷歌gson等
JavaBean序列化为Json,性能:Jackson > FastJson > Gson > Json-lib 同个结构
Jackson、FastJson、Gson类库各有优点,各有自己的专长
空间换时间,时间换空间
2、jackson处理相关自动
指定字段不返回:@JsonIgnore
指定日期格式:@JsonFormat(pattern="yyyy-MM-dd hh:mm:ss",locale="zh",timezone="GMT+8")
空字段不返回:@JsonInclude(Include.NON_NUll)
指定别名:@JsonProperty
Student实体类
private int id;
//指定别名
@JsonProperty("username")
//空字段不返回
@JsonInclude(JsonInclude.Include.NON_NULL)
private String name;
//指定字段不返回
@JsonIgnore
private String pass;
//添加一个日期,格式化日期
@JsonFormat(pattern="yyyy-MM-dd hh:mm:ss",locale="zh",timezone="GMT+8")
private Date birthday;
public Student(int id, String name, String pass, Date birthday) {
this.id = id;
// this.name = name;
this.pass = pass;
this.birthday = birthday;
}
。。。
Controller类
//测试json
@GetMapping("/testJson")
public Object testJson(){
return new Student(10,"mike","002204",new Date());
}
运行效果:
1.日期不格式化
2.密码忽视
3.用户名上添加别名
4.用户名为空时,就不显示