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"
}

相关推荐
4Forsee23 分钟前
【Android】消息机制
android·java·前端
骚戴30 分钟前
PDF或Word转图片(多线程+aspose+函数式接口)
java·开发语言
姓蔡小朋友33 分钟前
SpringDataRedis
java·开发语言·redis
CodeCraft Studio35 分钟前
国产化Excel处理控件Spire.XLS教程:如何使用 Java 将 TXT 文本转换为 Excel 表格
java·word·excel·spire·文档格式转换·txt转excel
朝新_44 分钟前
【SpringBoot】玩转 Spring Boot 日志:级别划分、持久化、格式配置及 Lombok 简化使用
java·spring boot·笔记·后端·spring·javaee
m0_748248021 小时前
Spring设计模式刨根问底
java·spring·设计模式
喝杯牛奶丶1 小时前
MySQL隔离级别:大厂为何偏爱RC?
java·数据库·mysql·面试
一 乐1 小时前
二手车销售|汽车销售|基于SprinBoot+vue的二手车交易系统(源码+数据库+文档)
java·前端·数据库·vue.js·后端·汽车
Mos_x2 小时前
15.<Spring Boot 日志>
java·后端
mm-q29152227292 小时前
Java并发编程从入门到进阶 多场景实战
java·开发语言