在SpringMVC中灵活配置FastJSON的序列化和反序列化

我们在使用FastJSON的时候有时候会指定一些不需要序列化或者反序列化的字段

4种方式

  1. @JSONField(serialize=false)
  2. 在字段前加transient  
  3. 使用fastjson的PropertyFilter
  4. new SimplePropertyPreFilter(TTown.class, "id","townname")直接过滤属性

上面4种方法看起来第一种和第二种是最简单的,但是不够灵活,我们如果在字段上这些修饰之后,那么在以后不管在程序的什么位置对该对象进行序列化或者反序列化的时候,都会受该注解的影响

但是有时候我们在程序种可能是只想在给用户返回数据的时候某些字段不进行反序列化,但是可能在我们服务器上进行序列化的时候又想要全部序列化,这时候加注解就不能实现了

我们在SpringMVC中将FastJsonHttpMessageConverter这个类配置为消息转换器,以此来将对象序列化成json返回给用户。

按照我们上面的想法,我们就只需要去对FastJsonHttpMessageConverter类进行配置,因为该类是控制返回给客户端的数据,也不会去影响到其他位置。

我们打开该类的源码,发现其中有一个FastJsonConfig类型的字段,很明显该字段是fastJson的配置字段,我们就可以通过注入我们自定义的配置来实现上面的效果了

<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
    <property name="fastJsonConfig">
        <bean class="com.alibaba.fastjson.support.config.FastJsonConfig">
            <!--
                指定过滤器
            -->
            <property name="serializeFilters">
                <list>
                    <ref bean="memberPropertyFilter"/>
                </list>
            </property>
        </bean>
    </property>
</bean>

实现我们自己的SerializeFilter,然后注入到FastJsonConfig中去

@Component
public class MemberPropertyFilter extends SimplePropertyPreFilter {

    public MemberPropertyFilter(String... properties) {
        super(Member.class, properties);
        getExcludes().add("id");
        getExcludes().add("password");
        getExcludes().add("lastLoadTime");
    }
}

SimplePropertyPreFilter 类是SerializeFilter接口的实现类

扫描二维码关注公众号,回复: 8944240 查看本文章

其内部维护了两个Set集合,一个Clazz,根据集合的名字我们就能看出来该集合中装的是什么

includes集合中装的是要进行序列化和反序列化的属性名称

excludes集合中装的是不进行序列化和反序列化的属性名称

clazz指定该过滤器适用于哪个Class,如果Class为空,则该过滤器适合于所有的类

SimplePropertyPreFilter类单独使用也非常的简单

SimplePropertyPreFilter simpFilter = new SimplePropertyPreFilter();
simpFilter.getIncludes().add("id");
JSON.toJSONString(obj,simpFilter);
发布了162 篇原创文章 · 获赞 44 · 访问量 8847

猜你喜欢

转载自blog.csdn.net/P19777/article/details/103450047