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

相关推荐
不能再留遗憾了3 小时前
【SpringCloud】Sentinel
spring·spring cloud·sentinel
源码_V_saaskw4 小时前
JAVA校园跑腿校园外卖源码校园外卖小程序校园代买帮忙外卖源码社区外卖源码小程序+公众号+h5
java·开发语言·微信小程序·小程序
源码哥_博纳软云4 小时前
JAVA同城预约服务家政服务美容美发洗车保洁搬家维修家装系统源码小程序+公众号+h5
java·开发语言·微信小程序·小程序
红尘客栈24 小时前
Kubernetes 集群调度
java·linux·网络·容器·kubernetes
编程岁月4 小时前
java面试-0203-java集合并发修改异常、快速/安全失败原理、解决方法?
java·开发语言·面试
whltaoin4 小时前
AI 超级智能体全栈项目阶段五:RAG 四大流程详解、最佳实践与调优(基于 Spring AI 实现)
java·人工智能·spring·rag·springai
junnhwan5 小时前
【苍穹外卖笔记】Day05--Redis入门与店铺营业状态设置
java·数据库·redis·笔记·后端·苍穹外卖
摇滚侠5 小时前
Spring Boot 3零基础教程,Spring Boot 特性介绍,笔记02
java·spring boot·笔记
Excuse_lighttime5 小时前
只出现一次的数字(位运算算法)
java·数据结构·算法·leetcode·eclipse
心勤则明5 小时前
Spring AI 文档ETL实战:集成text-embedding-v4 与 Milvus
人工智能·spring·etl