微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

fastJSON 笔记

faseJSON 结果为空时

空数组列表,结果是 []
空对象,结果是:{}
前端都可以直接给 js 用。 (感觉有点废话。o( ̄▽ ̄)o )

Java 泛型列表转 JSON
// 按 XXid 查询 hehe 列表
List<Hehe> heheList = heheService.getHeheByXXid(XXid);
//映射属性
NameFilter nameFilter = new NameFilter() { 
    public String process(Object source,String name,Object value) {
        if (name.equals("heheId")) {
            return "id";
        }else if (name.equals("heheName")) {
            return "name";
        }
        return name;
    }
};

//【转JSON,字段过滤 方法一 】 (以下用的是包含,也可以用排除。包含优先级较高,只要设置,排除就无效了。)
SimplePropertyPreFilter sppfilter = new SimplePropertyPreFilter();
sppfilter.getIncludes().add("heheId");
sppfilter.getIncludes().add("heheName");
sppfilter.getIncludes().add("heheValue");
sppfilter.getIncludes().add("heheRemark");
sppfilter.getIncludes().add("sheheImage");
//【转JSON,字段过滤 方法二 】,直接写出要序列化的属性 
//public SimplePropertyPreFilter(Class<?> clazz,String... properties){...}
sppfilter = new SimplePropertyPreFilter(Hehe.class,"heheId","heheName","heheValue");
//直接传属性名,它是一个 Class<?> clazz 为 null 的重载。不知其所以然 ( >﹏<) 
//sppfilter = new SimplePropertyPreFilter("heheId","heheName","heheValue");
JSON.toJSONString(specifications,sppfilter);

//只使用字段过滤(没有映射属性名)
JSON.toJSONString(specifications,sppfilter,SerializerFeature.UseSingleQuotes);

//【字段过滤】【映射属性名】两个过滤器放进数据,即可同时使用
//转JSON,支持数组传多个【过滤器】,多个【SerializerFeature】直拉往加后参数就行了,当然也支持传数组(如果多次使用,创建个数组方便些)
//Serializefilter[] filterarr = {nameFilter,sppfilter};
//JSON.toJSONString(specifications,filterarr,SerializerFeature.UseSingleQuotes);

/** * 如果hehe 有子对象 haha:{ hahaId: 1,heheId: 333,hahaName: "haha老大" } 想避免 haha 里的 heheId 被序列化: * SimplePropertyPreFilter sppfilter = new SimplePropertyPreFilter(SmartSite.class,"siteId","siteNumber","haha","hahaName"); * SimplePropertyPreFilter sppfilter2 = new SimplePropertyPreFilter(SmartSiteConfig.class,"configSortName"); * 转JSON,多个过滤器用数组传参 * Serializefilter[] filterarr = {nfilter,sppfilter2}; * 【2B注意】子对象的属性,只有在子对象被序列化的前提下,才会出来 */
fastJSON 序列化时定义属性顺序
//fastJSON序列化时定义属性顺序(所有字段都要列出来,否则无效)
@JSONType(orders={"heheId","heheValue","heheRemark","sheheImage"})
public class heheBean{
    private String sheheImage;
    private Integer heheId;
    private Integer heheValue;
    private String heheRemark;
    private String heheName;

    //----------- getter setter begin ----------
    ...
    //----------- getter setter end ----------
}

参考资料

fastjson SerializerFeature详解 【传送门】
Fastjson API SerializeFilte r简介

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐