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

相关推荐
郑州光合科技余经理10 分钟前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
大大水瓶1 小时前
Tomcat
java·tomcat
dustcell.1 小时前
haproxy七层代理
java·开发语言·前端
游离态指针1 小时前
以为发消息=下单成功?RabbitMQ从0到秒杀实战的完整踩坑笔记
java
BD_Marathon1 小时前
工厂方法模式
android·java·工厂方法模式
玹外之音2 小时前
Spring AI MCP 无状态服务器实战:构建AI智能用户管理系统
java·后端
what丶k2 小时前
Spring AI 多模态开发全解析:从入门到企业级落地
后端·spring·ai编程
java干货2 小时前
Redis 的 ZipList 是什么?它是怎么解决内存碎片问题的?
java
失重外太空啦2 小时前
Tomcat
java·服务器·tomcat
屎到临头想搅便2 小时前
TOMCAT
java·tomcat