fastjson自定义解析格式

博客详细介绍了Fastjson的SerializerFeature枚举的各种属性及其作用,包括如何处理空值、日期格式、特殊字符转义等,并给出了使用示例,帮助理解如何在序列化和反序列化过程中定制输出格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  @Test
    public void gsonTest() {
        user user = new User();
        ValueFilter filter = (clazz, s, v) -> {
            if (v == null) {
                return "user";
            }
            return v;
        };
        System.out.println(JSON.toJSONString(user,filter,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.PrettyFormat,
                SerializerFeature.WriteMapNullValue
        ));


    }

SerializerFeature属性解释
名称    含义    备注
QuoteFieldNames    输出key时是否使用双引号,默认为true     
UseSingleQuotes    使用单引号而不是双引号,默认为false     
WriteMapNullValue    是否输出值为null的字段,默认为false     
WriteEnumUsingToString    
Enum输出name()或者original,默认为false

 
目前版本的fastjon默认对enum对象使用WriteEnumUsingName属性,因此会将enum值序列化为其Name。
使用WriteEnumUsingToString方法可以序列化时将Enum转换为toString()的返回值;同时override toString函数能够将enum值输出需要的形式。但是这样做会带来一个问题,对应的反序列化使用的Enum的静态方法valueof可能无法识别自行生成的toString(),导致反序列化出错。
如果将节省enum序列化后的大小,可以将enum序列化其ordinal值,保存为int类型。fastJson在反序列化时,如果值为int,则能够使用ordinal值匹配,找到合适的对象。
fastjson要将enum序列化为ordinal只需要禁止WriteEnumUsingName feature。
首先根据默认的features排除WriteEnumUsingName,然后使用新的features序列化即可。

int features=SerializerFeature.config(JSON.DEFAULT_GENERATE_FEATURE, SerializerFeature.WriteEnumUsingName, false)
JSON.toJSONString(obj,features,SerializerFeature.EMPTY);

 
 

 
WriteEnumUsingName          
UseISO8601DateFormat    Date使用ISO8601格式输出,默认为false     
WriteNullListAsEmpty    List字段如果为null,输出为[],而非null     
WriteNullStringAsEmpty    字符类型字段如果为null,输出为”“,而非null     
WriteNullNumberAsZero    数值字段如果为null,输出为0,而非null     
WriteNullBooleanAsFalse    Boolean字段如果为null,输出为false,而非null     
SkipTransientField    如果是true,类中的Get方法对应的Field是transient,序列化时将会被忽略。
默认为true     
SortField    按字段名称排序后输出。默认为false     
WriteTabAsSpecial    把\t做转义输出,默认为false    不推荐
PrettyFormat    结果是否格式化,默认为false    不推荐
WriteClassName    序列化时写入类型信息,默认为false。反序列化是需用到    不推荐
DisableCircularReferenceDetect    消除对同一对象循环引用的问题,默认为false
当进行toJSONString的时候,默认如果重用对象的话,会使用引用的方式进行引用对象。

 [  
      {  
        "$ref": "$.itemSkuList[0].itemSpecificationList[0]"  
      },   
      {  
        "$ref": "$.itemSkuList[1].itemSpecificationList[0]"  
      }  
    ]  
 

循环引用
很多场景中,我们需要序列化的对象中存在循环引用,在许多的json库中,这会导致stackoverflow。在功能强大的fastjson中,你不需要担心这个问题。例如:

A a = new A();  
B b = new B(a);  
a.setB(b);  
String text = JSON.toJSONString(a); //{"b":{"a":{"$ref":".."}}}  
A a1 = JSON.parseObject(text, A.class);  
Assert.assertTrue(a1 == a1.getB().getA());  
 

引用是通过"$ref"来表示的

引用描述

"$ref":".."  上一级
"$ref":"@"   当前对象,也就是自引用
"$ref":"$"   根对象
"$ref":"$.children.0"   基于路径的引用,相当于 root.getChildren().get(0)
 

 
 

不推荐
WriteSlashAsSpecial    对斜杠’/’进行转义    不推荐
BrowserCompatible    将中文都会序列化为\uXXXX格式,字节数会多一些,但是能兼容IE 6,默认为false    不推荐
WriteDateUseDateFormat    全局修改日期格式,默认为false。
JSON.DEFFAULT_DATE_FORMAT = “yyyy-MM-dd”;
JSON.toJSONString(obj, SerializerFeature.WriteDateUseDateFormat);    不推荐
DisableCheckSpecialChar    一个对象的字符串属性中如果有特殊字符如双引号,将会在转成json时带有反斜杠转移符。如果不需要转义,可以使用这个属性。默认为false    不推荐
NotWriteRootClassName    含义    不推荐
BeanToArray    将对象转为array输出    不推荐
WriteNonStringKeyAsString         不推荐
NotWriteDefaultValue         不推荐
BrowserSecure         不推荐
IgnoreNonFieldGetter         不推荐
————————————————
版权声明:本文为优快云博主「琦彦」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.youkuaiyun.com/fly910905/article/details/78474813

fastjson:SerializerFeature属性使用_琦彦的博客-优快云博客_fastjson serializerfeaturefastjson:SerializerFeature源码 Source code recreated from a .class file by IntelliJ IDEA// (powered by Fernflower decompiler)//package com.alibaba.fastjson.serializer;public enum SerializerF...https://blog.youkuaiyun.com/fly910905/article/details/78474813?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522165112710816781683976524%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=165112710816781683976524&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduend~default-1-78474813.142^v9^control,157^v4^control&utm_term=SerializerFeature&spm=1018.2226.3001.4187 

package com.alibaba.fastjson.serializer;

public enum SerializerFeature {


    QuoteFieldNames,//输出key时是否使用双引号,默认为true 


    /**
     *
     */


    UseSingleQuotes,//使用单引号而不是双引号,默认为false


    /**
     *
     */


    WriteMapNullValue,//是否输出值为null的字段,默认为false 


    /**
     *
     */


    WriteEnumUsingToString,//Enum输出name()或者original,默认为false


    /**
     *
     */


    UseISO8601DateFormat,//Date使用ISO8601格式输出,默认为false


    /**
     * @since 1.1
     */


    WriteNullListAsEmpty,//List字段如果为null,输出为[],而非null 


    /**
     * @since 1.1
     */


    WriteNullStringAsEmpty,//字符类型字段如果为null,输出为"",而非null 


    /**
     * @since 1.1
     */


    WriteNullNumberAsZero,//数值字段如果为null,输出为0,而非null 


    /**
     * @since 1.1
     */


    WriteNullBooleanAsFalse,//Boolean字段如果为null,输出为false,而非null


    /**
     * @since 1.1
     */


    SkipTransientField,//如果是true,类中的Get方法对应的Field是transient,序列化时将会被忽略。默认为true


    /**
     * @since 1.1
     */


    SortField,//按字段名称排序后输出。默认为false


    /**
     * @since 1.1.1
     */


    @Deprecated


    WriteTabAsSpecial,//把\t做转义输出,默认为false


    /**
     * @since 1.1.2
     */


    PrettyFormat,//结果是否格式化,默认为false


    /**
     * @since 1.1.2
     */


    WriteClassName,//序列化时写入类型信息,默认为false。反序列化是需用到


    /**
     * @since 1.1.6
     */


    DisableCircularReferenceDetect,//消除对同一对象循环引用的问题,默认为false


    /**
     * @since 1.1.9
     */


    WriteSlashAsSpecial,//对斜杠'/'进行转义


    /**
     * @since 1.1.10
     */


    BrowserCompatible,//将中文都会序列化为\uXXXX格式,字节数会多一些,但是能兼容IE 6,默认为false


    /**
     * @since 1.1.14
     */


    WriteDateUseDateFormat,//全局修改日期格式,默认为false。JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd";JSON.toJSONString(obj, SerializerFeature.WriteDateUseDateFormat);


    /**
     * @since 1.1.15
     */


    NotWriteRootClassName,//暂不知,求告知


    /**
     * @since 1.1.19
     */


    DisableCheckSpecialChar,//一个对象的字符串属性中如果有特殊字符如双引号,将会在转成json时带有反斜杠转移符。如果不需要转义,可以使用这个属性。默认为false 


    /**
     * @since 1.1.35
     */

    private SerializerFeature() {
        mask = (1 << ordinal());
    }

    private final int mask;

    public final int getMask() {
        return mask;
    }

    public static boolean isEnabled(int features, SerializerFeature feature) {
        return (features & feature.getMask()) != 0;
    }

    public static int config(int features, SerializerFeature feature, boolean state) {
        if (state) {
            features |= feature.getMask();
        } else {
            features &= ~feature.getMask();
        }
        return features;
    }
    }
 

 

fastjson中SerializerFeature的用法及中文注解 - Dyaqi - 博客园中文注解、使用https://www.cnblogs.com/dyaqi/p/14793976.html 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Silence丶你的名字

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值