Spring注解之json 数据处理

目录

[1. 过滤 json 数据](#1. 过滤 json 数据)

[2. 格式化 json 数据](#2. 格式化 json 数据)

[3. 扁平化对象](#3. 扁平化对象)


1. 过滤 json 数据

@JsonIgnoreProperties 作用在类上用于过滤掉特定字段不返回或者不解析。

java 复制代码
//生成json时将userRoles属性过滤
@JsonIgnoreProperties({"userRoles"})
public class User {
​
    private String userName;
    private String fullName;
    private String password;
    @JsonIgnore
    private List<UserRole> userRoles = new ArrayList<>();
}

@JsonIgnore一般用于类的属性上,作用和上面的@JsonIgnoreProperties 一样。

java 复制代码
public class User {
​
    private String userName;
    private String fullName;
    private String password;
   //生成json时将userRoles属性过滤
    @JsonIgnore
    private List<UserRole> userRoles = new ArrayList<>();
}
2. 格式化 json 数据

@JsonFormat一般用来格式化 json 数据。:

比如:

java 复制代码
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", timezone="GMT")
private Date date;
3. 扁平化对象
java 复制代码
@Getter
@Setter
@ToString
public class Account {
    @JsonUnwrapped
    private Location location;
    @JsonUnwrapped
    private PersonInfo personInfo;
​
  @Getter
  @Setter
  @ToString
  public static class Location {
     private String provinceName;
     private String countyName;
  }
  @Getter
  @Setter
  @ToString
  public static class PersonInfo {
    private String userName;
    private String fullName;
  }
}

未扁平化之前:

java 复制代码
{
    "location": {
        "provinceName":"河北",
        "countyName":"廊坊"
    },
    "personInfo": {
        "userName": "ww1234",
        "fullName": "shanghai"
    }
}

使用@JsonUnwrapped 扁平对象之后:

java 复制代码
@Getter
@Setter
@ToString
public class Account {
    @JsonUnwrapped
    private Location location;
    @JsonUnwrapped
    private PersonInfo personInfo;
    ......
}
java 复制代码
{
  "provinceName":"河北",
  "countyName":"廊坊",
  "userName": "ww1234",
  "fullName": "shanghai"
}

相关推荐
only-qi3 小时前
146. LRU 缓存
java·算法·缓存
xuxie135 小时前
SpringBoot文件下载(多文件以zip形式,单文件格式不变)
java·spring boot·后端
重生成为编程大王5 小时前
Java中的多态有什么用?
java·后端
666和7775 小时前
Struts2 工作总结
java·数据库
中草药z5 小时前
【Stream API】高效简化集合处理
java·前端·javascript·stream·parallelstream·并行流
野犬寒鸦5 小时前
力扣hot100:搜索二维矩阵 II(常见误区与高效解法详解)(240)
java·数据结构·算法·leetcode·面试
zru_96025 小时前
centos 系统如何安装open jdk 8
java·linux·centos
码熔burning6 小时前
Spring Security 深度学习(六): RESTful API 安全与 JWT
安全·spring·restful·springsecurity
LiRuiJie6 小时前
深入剖析Spring Boot / Spring 应用中可自定义的扩展点
java·spring boot·spring