使用SimplePropertyPreFilter过滤属性

技术文档网 2021-05-08

需要根据不同的环境返回定制化返回属性时,可以使用SimplePropertyPreFilter。

SimplePropertyPreFilter接口

SimplePropertyPreFilter的代码接口如下:

public class SimplePropertyPreFilter implements PropertyPreFilter {
    public SimplePropertyPreFilter(String... properties){
          this(null, properties);
    }

    public SimplePropertyPreFilter(Class<?> clazz, String... properties){
          // ... ...
    }

    public Class<?> getClazz() {
          return clazz;
    }

    public Set<String> getIncludes();

    public Set<String> getExcludes();

    /**
     * @since 1.2.9
     */
    public int getMaxLevel();

    /**
     * @since 1.2.9
     */
    public void setMaxLevel(int maxLevel)

    //...
}

你可以配置includes、excludes。当class不为null时,针对特定类型;当class为null时,针对所有类型。

当includes的size > 0时,属性必须在includes中才会被序列化,excludes优先于includes。

使用介绍

在1.1.23版本之后,JSON提供新的序列化接口toJSONString,如下:

String toJSONString(Object, SerializeFilter, SerializerFeature...);

使用方式如下:

VO vo = new VO();

vo.setId(123);
vo.setName("flym");

SimplePropertyPreFilter filter = new SimplePropertyPreFilter(VO.class, "name");
Assert.assertEquals("{\"name\":\"flym\"}", JSON.toJSONString(vo, filter));

public static class VO {
      private int    id;
      private String name;

      public int getId() {
          return id;
      }
      public void setId(int id) {
          this.id = id;
      }

      public String getName() {
          return name;
      }
      public void setName(String name) {
          this.name = name;
    }
}

如果你需要在类级别配置Filter,可以看这里

相关文章

  1. 基于-SLF4J-MDC-机制的日志链路追踪配置属性

    ums: # ================ 基于 SLF4J MDC 机制的日志链路追踪配置属性 ================ mdc: # 是否支持基于 SLF4J MDC

  2. ajax-跨域访问

    ajax 跨域访问 &lt;!DOCTYPE html&gt; &lt;html xmlns:th="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt;

  3. 给第三方登录时用的数据库表-user_connection-与-auth_token-添加-redis-cache

    spring: # 设置缓存为 Redis cache: type: redis # redis redis: host: 192.168.88.88 port

  4. Java动态代理

    Jdk动态代理 通过InvocationHandler和Proxy针对实现了接口的类进行动态代理,即必须有相应的接口 应用 public class TestProxy { public

  5. Java读取classpath中的文件

    public void init() { try { //URL url = Thread.currentThread().getContextClassLo

随机推荐

  1. 基于-SLF4J-MDC-机制的日志链路追踪配置属性

    ums: # ================ 基于 SLF4J MDC 机制的日志链路追踪配置属性 ================ mdc: # 是否支持基于 SLF4J MDC

  2. ajax-跨域访问

    ajax 跨域访问 &lt;!DOCTYPE html&gt; &lt;html xmlns:th="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt;

  3. 给第三方登录时用的数据库表-user_connection-与-auth_token-添加-redis-cache

    spring: # 设置缓存为 Redis cache: type: redis # redis redis: host: 192.168.88.88 port

  4. Java动态代理

    Jdk动态代理 通过InvocationHandler和Proxy针对实现了接口的类进行动态代理,即必须有相应的接口 应用 public class TestProxy { public

  5. Java读取classpath中的文件

    public void init() { try { //URL url = Thread.currentThread().getContextClassLo