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

相关推荐
都叫我大帅哥28 分钟前
深入浅出 Resilience4j:Java 微服务的“免疫系统”实战指南
java·spring cloud
Cao_Shixin攻城狮3 小时前
Flutter运行Android项目时显示java版本不兼容(Unsupported class file major version 65)的处理
android·java·flutter
Dcs5 小时前
还在用 Arrays.hashCode?Java 自己也能写出更快的版本!
java
fouryears_234177 小时前
Spring,Spring Boot 和 Spring MVC 的关系以及区别
java·spring boot·spring·mvc
阿葱(聪)8 小时前
java 在k8s中的部署流程
java·开发语言·docker·kubernetes
浮生带你学Java8 小时前
2025Java面试题及答案整理( 2025年 7 月最新版,持续更新)
java·开发语言·数据库·面试·职场和发展
板板正8 小时前
SpringAI——提示词(Prompt)、提示词模板(PromptTemplate)
java·spring boot·ai·prompt
板板正8 小时前
SpringAI——对话记忆
java·spring boot·ai
期待のcode8 小时前
图片上传实现
java·前端·javascript·数据库·servlet·交互
李长渊哦9 小时前
深入理解Java中的Map.Entry接口
java·开发语言