Fastjson序列化Null字段丢失解决方法


//jsonString = JSON.toJSONString(data);  //值为Null的字段丢失,改下面
jsonString = JSON.toJSONString(data,SerializerFeature.WriteMapNullValue); 
 //WriteMapNullValue——–是否输出值为null的字段,默认为false 

Fastjson的SerializerFeature序列化属性 :

  • QuoteFieldNames———-输出key时是否使用双引号,默认为true 
  • WriteMapNullValue——–是否输出值为null的字段,默认为false 
  • WriteNullNumberAsZero—-数值字段如果为null,输出为0,而非null 
  • WriteNullListAsEmpty—–List字段如果为null,输出为[],而非null 
  • WriteNullStringAsEmpty—字符类型字段如果为null,输出为”“,而非null 
  • WriteNullBooleanAsFalse–Boolean字段如果为null,输出为false,而非null
在Spring Boot中使用Fastjson作为JSON序列化器,首先需要添加Fastjson的依赖项,可以在pom.xml文件中添加以下依赖项: ```xml <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.75</version> </dependency> ``` 然后,在Spring Boot应用程序的配置文件中,可以使用以下属性来配置Fastjson的行为: ```properties # 配置Fastjson为默认的JSON序列化器 spring.http.converters.preferred-json-mapper=fastjson # 配置Fastjson的特性 spring.fastjson.serializer.xxx=yyy ``` 其中,xxx可以为以下任意一个特性: | 属性 | 描述 | | ---- | ---- | | writeMapNullValue | 是否输出值为null字段,默认为false | | writeNullListAsEmpty | 是否输出空的list,默认为false | | writeNullStringAsEmpty | 是否输出空的字符串,默认为false | | writeNullBooleanAsFalse | 是否输出null的布尔值,默认为false | | writeDateUseDateFormat | 是否使用日期格式化,默认为false | | notWriteRootClassName | 是否输出类名,默认为false | | sortField | 是否按照字段名称排序后输出,默认为false | | indentOutput | 是否缩进输出,默认为false | | quoteFieldNames | 是否输出key作为双引号包围的字符串,默认为true | | ignoreNonFieldGetter | 是否忽略getter方法的返回值,默认为false | | ignoreErrorGetter | 是否忽略getter方法的错误,默认为false | 其中,yyy为相应的特性值。例如: ```properties # 配置Fastjson为默认的JSON序列化器 spring.http.converters.preferred-json-mapper=fastjson # 配置Fastjson的特性 spring.fastjson.serializer.writeMapNullValue=true spring.fastjson.serializer.writeNullListAsEmpty=true spring.fastjson.serializer.writeNullStringAsEmpty=true spring.fastjson.serializer.writeNullBooleanAsFalse=true spring.fastjson.serializer.writeDateUseDateFormat=true spring.fastjson.serializer.notWriteRootClassName=true spring.fastjson.serializer.sortField=true spring.fastjson.serializer.indentOutput=true spring.fastjson.serializer.quoteFieldNames=false spring.fastjson.serializer.ignoreNonFieldGetter=true spring.fastjson.serializer.ignoreErrorGetter=true ``` 除了上述属性外,还可以使用@JSONField注解来控制序列化的行为。例如: ```java public class MyObject { @JSONField(name = "myProperty", serialize = false) private String myProperty; // getters and setters } ``` 这将使Fastjson序列化时将Java对象属性名“myProperty”映射到JSON属性名“myProperty”,并且忽略该属性的序列化
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值