JSON.toJSONString格式化成json字符串时保留null属性

第一篇   JSON.toJSONString格式化成json字符串时保留null属性

原文:https://blog.csdn.net/qq_34412985/article/details/81985459

使用阿里的

com.alibaba.fastjson.JSON

格式化时,默认null属性会被过滤掉,可以设置不过滤null,参考作者的博文

public static String parseScriptJsonStringWithNullValue(Object obj) {

   if (obj == null || (obj instanceof Undefined)) {

      return null;

   }

   return JSON.toJSONString(obj, new SerializeFilter[]{scriptArrayFilter}, SerializerFeature.WriteMapNullValue);

}

 

 

指定这个参数即可

SerializerFeature.WriteMapNullValue

 

属性说明

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

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

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

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

WriteNullStringAsEmpty—字符类型字段如果为null,输出为”“,而非null

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

 

 

例子:

String ret = JSON.toJSONStringWithDateFormat(returnValue, "yyyy-MM-dd HH:mm:ss",
                SerializerFeature.PrettyFormat,
                    // 保留map空的字段
                    SerializerFeature.WriteMapNullValue,
                    // 将String类型的null转成""
                    SerializerFeature.WriteNullStringAsEmpty,
                    // 将Number类型的null转成0
                    SerializerFeature.WriteNullNumberAsZero,
                    // 将List类型的null转成[]
                    SerializerFeature.WriteNullListAsEmpty,
                    // 将Boolean类型的null转成false
                    SerializerFeature.WriteNullBooleanAsFalse,
                    // 避免循环引用
                    SerializerFeature.DisableCircularReferenceDetect
                );

 

第二篇  springboot 处理返回结果中字段为空或为null,不展示字段的问题(字段展示不全)

package com.aiqin.mgs.market.api.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * description: fastjson处理返回的参数为null、或者不返回
 * date: 2019/11/22 15:03
 * author: hantao
 * version: 1.0
 * springboot 处理返回结果中字段为空或为null,不展示字段的问题(字段展示不全)
 */
@Configuration
public class FastJsonConfiguration extends WebMvcConfigurationSupport {

    /**
     * 使用阿里 fastjson 作为JSON MessageConverter
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonConfig config = new FastJsonConfig();
        config.setSerializerFeatures(
                // 保留map空的字段
                SerializerFeature.WriteMapNullValue,
                // 将String类型的null转成""
                SerializerFeature.WriteNullStringAsEmpty,
                // 将Number类型的null转成0
                SerializerFeature.WriteNullNumberAsZero,
                // 将List类型的null转成[]
                SerializerFeature.WriteNullListAsEmpty,
                // 将Boolean类型的null转成false
                SerializerFeature.WriteNullBooleanAsFalse,
                // 避免循环引用
                SerializerFeature.DisableCircularReferenceDetect);

        converter.setFastJsonConfig(config);
        converter.setDefaultCharset(Charset.forName("UTF-8"));
        List<MediaType> mediaTypeList = new ArrayList<>();
        // 解决中文乱码问题,相当于在Controller上的@RequestMapping中加了个属性produces = "application/json"
        mediaTypeList.add(MediaType.APPLICATION_JSON);
        converter.setSupportedMediaTypes(mediaTypeList);
        converters.add(converter);
    }

    /**
     * 整合了swagger需要配置swagger拦截
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html","index.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/META-INF/resources/static/");
    }

}

 

  • 1
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
根据引用\[1\]中的代码,使用JSONUtil.toJsonStr()方法序列化对象,默认会将对象中值为空的属性过滤掉。如果需要保留空值属性,可以使用JSONUtil.parseObj()方法,并将第二个参数设置为false。这样就可以将对象转换为JSON字符串包含空值属性。\[2\] 另外,根据引用\[3\]中的代码,如果需要格式化JSON字符串保留null属性,可以使用JSON.toJSONString()方法,并设置SerializerFeature.WriteMapNullValue参数。这样就可以将null属性保留JSON字符串中。 #### 引用[.reference_title] - *1* *2* [使用Hutool-json工具包中的JSONUtil.toJsonStr()方法序列化,对象数据中值为null属性被过滤的问题](https://blog.csdn.net/qq_28742063/article/details/127771933)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [JSON.toJSONString格式化json字符串保留null属性](https://blog.csdn.net/weixin_40918067/article/details/117376294)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值