杰客网络

杰客网络个人博客

Springboot 过滤字段属性 返回JSON

方法1:在不想序列化的字段上加注解JsonProperty:

@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)//Jackson
@JSONField(serialize = false)//fastjson
String password;

使用 SimpleFilterProvider

定义filter,设置序列字段

/**

  • 只序列化 field1,field2
    1. 使用 SimpleBeanPropertyFilter 设置,需要序列化的字段。
    1. 使用 SimpleFilterProvider 添加 filter 。
    1. 将 filter 添加到 实体类上。
  • @return

*/
@GetMapping("/filtering4")
public MappingJacksonValue retrieveSomeBean4() {

SomeBean someBean = new SomeBean("value1", "value2", "value3");
ResEntity ret = new ResEntity("1", "OK", someBean);

// 要序列化的字段
String fields = "field1,field2";
FilterProvider filters = filter("1", "SomeBeanFilter", fields.split(","));
MappingJacksonValue mapping = new MappingJacksonValue(ret);
mapping.setFilters(filters);

return mapping;

}

实体类添加注解(SomeBeanFilter:上面定义的filter名)

@JsonFilter("SomeBeanFilter")
public class SomeBean {

定义filter名方法

/**

  • 过滤 JSON 数据。

*

  • @param argType 过滤类型(1:过滤想要的;2:过滤不想要的)
  • @param filterName
  • @param propertyes
  • @return

*/
public FilterProvider filter(String argType, String filterName, String... propertyes) {

FilterProvider filter;

if ("1".equals(argType)) {

  // 过滤想要的
  filter = new SimpleFilterProvider().addFilter(
          filterName, SimpleBeanPropertyFilter.filterOutAllExcept(propertyes));
} else {
  // 过滤不想要的
  filter = new SimpleFilterProvider().addFilter(
          filterName,
          SimpleBeanPropertyFilter.serializeAllExcept(propertyes));

}

return filter;

}
}

自定义过滤注解

(收藏)Spring MVC 更灵活的控制 json 返回(自定义过滤字段)

有用链接