fastjson生成json时Null转为空字符串""或者不展示问题解决

fastjson生成json时Null转为空字符串““或者不展示问题解决 原文地址:https://blog.youkuaiyun.com/github_39557053/article/details/86609985?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-4.baidujs&dist_request_id=1328760.12081.16172577990368613&depth_1-utm_sourc 阅读详情
AI摘要

本文介绍在使用FastJSON进行序列化时如何处理空值,通过设置SerializerFeature.WriteNullStringAsEmpty属性,使null和空字符串能够正确显示,避免了在系统对接中因字段为空而引发的问题。


原文地址:https://blog.youkuaiyun.com/qq_31138523/article/details/65627965


在开发过程中,系统间对接是再正常不过的行为了,但是在对接过程中由于各种原因可能为空字段必须显示为空字符串,或者不显示,经过查询发现一枚神器,记录一下,以免忘记。 
   举个栗子:

Map < String , Object > jsonMap = new HashMap< String , Object>();  
jsonMap.put("a",1);  
jsonMap.put("b","");  
jsonMap.put("c",null);  
jsonMap.put("d","wuzhuti.cn");  
  
String str = JSONObject.toJSONString(jsonMap);  
System.out.println(str);  
//输出结果:{"a":1,"b":"",d:"wuzhuti.cn"}  

从输出结果可以看出,null对应的key已经被过滤掉;这明显不是我们想要的结果,这时我们就需要用到fastjson的SerializerFeature序列化属性。fastjson提供了此方法解决这个问题:JSONObject.toJSONString(Object object, SerializerFeature... features)

Fastjson的SerializerFeature序列化属性

QuoteFieldNames———-输出key时是否使用双引号,默认为true 
WriteMapNullValue——–是否输出值为null的字段,默认为false 
WriteNullNumberAsZero—-数值字段如果为null,输出为0,而非null 
WriteNullListAsEmpty—–List字段如果为null,输出为[],而非null 
WriteNullStringAsEmpty—字符类型字段如果为null,输出为”“,而非null 
WriteNullBooleanAsFalse–Boolean字段如果为null,输出为false,而非null

 使用此方法后效果如下:

Map < String , Object > jsonMap = new HashMap< String , Object>();  
jsonMap.put("a",1);  
jsonMap.put("b","");  
jsonMap.put("c",null);  
jsonMap.put("d","wuzhuti.cn");  
  
String str = JSONObject.toJSONString(jsonMap,SerializerFeature.WriteNullStringAsEmpty);  
System.out.println(str);  
//输出结果:{"a":1,"b":"","c":"","d":"wuzhuti.cn"}  

 

支持向量机算法(带你了解原理 实践) 支持向量机作为一种强大的分类算法,在各个领域都取得了显著的成果。其基于统计学习理论的原理使得它能够在高维空间中找到最优分类超平面,并通过核函数处理非线性问题。 阅读详情

相关推荐

【MicroPython编程-ESP32篇:设备驱动】-BNO08X系列传感器驱动

BNO08X 系列(BNO085/BNO086)是一款系统级封装 (SiP),集成了三轴加速度计、三轴陀螺仪、磁力计以及运行 CEVA SH-2 固件的 32 位 ARM® Cortex™-M0+ 微控制器。SH-2 包含 MotionEngine™ 软件,该软件提供复杂的信号处理算法来处理传感器数据,并提供精确的实时 3D 姿态、航向、校准加速度和校准角速度,以及更高级的上下文输出。BNO08X 集成在一个 28 引脚 LGA 封装中,尺寸为 3.8mm x 5.2mm x 1.1mm。它兼容 Andro

视觉与物联智能 696

Fastjson使用:将json字符串转对象为空问题

问题背景 在一次更改老项目中,因为想使用构造器方便点,就在原来的代码基础上增加了一个有参构造器,原来的代码是没有设置构造器的。(没有设置的话使用默认的一个无参构造器) 。 然后因为我新创建的有参构造器会覆盖原来的无参构造器。 导致原先的json转对象会出现转出来的对象为空问题。 大致代码如下: 示例代码 @Setter @Getter @AllArgsConstructor @ToString public class FastjsonTest { private String id;

qq_37716298的博客 3343

华为OD面试手撕真题目录

2026最新华为OD面试手撕真题 , 提供Java、C++、Python、Go、JavaScript源码实现,并提供完整思路讲解.

qq_45776114的博客 1万+

fastjson 把null属性转成空字符串

在使用FastJson解析数据的时候,如果API中返回的实体类中某个属性是null值的话,该属性是会被过滤掉的。 但是往往这个属性我们需要它不被过滤掉,更希望它转成空字符串等形式来展示。这个时候可以使用FastJson的serialzeFeatures属性来实现这个效果。 很简单,只需要在实体类的属性上加上注解 @JSONField(serialzeFeatures= {Serialize...

青藤光年的博客 1万+

还原 Windows 环境变量的默认值

有时候,我们可能需要还原环境变量的默认值,以修复可能的配置问题或恢复系统的正常运行。如果您只想还原某个特定的环境变量,可以跳过删除其他变量的步骤,仅删除需要还原的变量即可。在“环境变量”对话框中,继续向下滚动到“系统变量”部分。请注意,在执行以下步骤之前,您应该备份当前的环境变量设置,以便在需要时可以还原。在删除所有需要还原的环境变量后,点击“确定”按钮关闭“环境变量”对话框。在“用户变量”部分,选择需要还原的变量,然后点击“删除”按钮。在“高级”选项卡下方的“环境变量”部分,点击“环境变量”按钮。

PvDeveloper的博客 6342

RK3588 部署 YOLO26 目标检测:PT → ONNX → RKNN 全流程

YOLO26n 在 RK3588 上 INT8 量化后 NPU 推理约 15ms,系统 FPS 约 55,可以覆盖边缘端实时检测需求。模型从 PT 到 RKNN 的转换要用opset=11避免算子兼容问题。先用 YOLO26n + 640 输入跑通全链路,确认推理结果正确后再做性能调优。

m0_64661770的博客 306

【springboot进阶】基于starter项目构建(二)构建starter项目-fastjson

构建springboot 自定义 starter,使用 fastjson 作为 springboot 的消息解析器,替代默认的jackson

889

YOLOv11知识蒸馏实战:让小模型拥有大模型90%精度,速度提升3倍的终极教程

在self.alpha = alpha # 蒸馏损失权重self.temperature = temperature # 温度系数,控制分布平滑度# 输出分布蒸馏(KL散度损失)# 中间特征蒸馏(MSE损失,对齐中间层特征)# 总蒸馏损失知识蒸馏是YOLOv11在“小模型高性能部署”场景的“破局之法”——它让小模型能“站在大模型的肩膀上”,兼具速度与精度。从损失函数定义到多阶段训练,再到实战落地,本教程已为你铺就了一条清晰的路径。

m0_64661770的博客 803

JSON.toJSONString的坑有些字段没有了

1.问题 在使用fastjson中的JSON.toJSONString方法将对象转换成json字符串的时候,发现有些字段没有了。如: 1 2 3 4 5 6 7 8 publicstaticvoidmain(String[] args) { Map<String,Object>map=newHashMap<>(); map.put("id"...

万事俱备,就差一个程序员了 7095

【ROS2】RViz2加载URDF模型文件

1)运行RViz2rviz22)添加组件:RobotModel3)选择通过文件添加4)选择URDF文件,此时会报错,需要修改Fixed Frame为map即可

郭老二 1451

STM32(HAL库)驱动HC-SR04测距模块

本文介绍通过STM32F103C8T6单片机对HC-SR04测距模块进行驱动,并且通过串口对数据进行打印。

weixin_44597885的博客 2205

SpringBoot 配置 FastJson null转字符串

【代码】SpringBoot 配置 FastJson null转字符串。

掐指一算乀缺钱 1297

Python代码加密与发布方案详解

本文详细介绍了多种Python代码保护方案,从基础加密到高级混淆,以及商业化发布的最佳实践。基础加密方案包括编译为字节码和使用PyArmor基础加密,适合临时保护和小项目。商业级加密方案如Cython编译和Nuitka完整打包,提供更高的保护强度和执行效率。高级混淆方案涉及控制流混淆、字符串加密和完整混淆工具链,进一步增加逆向难度。商业化发布方案则强调许可证系统集成、硬件绑定保护和完整发布流程。此外,文章还探讨了反逆向技术、最佳实践建议和常见问题解决方法。通过组合使用这些技术,可以构建出适合不同安全需求的P

数据知道的博客 1万+

fastjson生成json时Null转为空字符串""或者不展示

原文地址:http://wuzhuti.cn/2175.html 举个例子 生成JSON代码片段 [java]预览复制 Map<String,Object>jsonMap=newHashMap<String,Object>(); jsonMap.put("a",1); jsonMap.put("b",""); jsonMa...

开朗的奥特曼的博客 3万+

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

为什么设置了SerializerFeature.WriteNullStringAsEmpty,fastjson字段为null时不输出空字符串?

转自:https://segmentfault.com/q/1010000004216492 为什么fastjson字段为null时不输出空字符串? Map < String , Object > jsonMap = new HashMap< String , Object>(); jsonMap.put("a",1); jsonMap.put("b",...

u012534163的博客 2万+

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

springboot返回json时将null转为空字符串

我们通过jackson来处理这种情况: package com.media.config; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializerProvid

weixin_40145819的博客 1630

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

问题:fastjson字段为null时不输出空字符串问题

问题 Map < String , Object > jsonMap = new HashMap< String , Object>(); jsonMap.put("a",1); jsonMap.put("b",""); jsonMap.put("c",null); jsonMap.put("d","wuzhuti.cn"); String str...

HUMM 1721

com.alibaba.fastjson.JSON.toJSONString使用时值为NULL的属性被忽略的问题

在使用alibaba的fastjson做json序列化时,由于上游系统对于json的要求过于严格,才发现了JSON.toJSONString使用时值为NULL的属性被忽略的问题。如果某个属性的值为null,再被序列化为字符串是默认会被忽略,原因和解决方式详述如下,提示:以下是本篇文章正文内容,下面案例可供参考。...

cheers_bin的博客 1万+

SpringBoot项目Json中的空值处理,将null转为空字符串"",空list转为空数组等

本篇使用fastjson进行空值null处理 Jackson的请看:https://blog.youkuaiyun.com/qq_31183727/article/details/99539115 项目中之前用的null值转空串方法,将空list也转换为了"",不适合需求,之后在网上找的方法修改后,适用现在的需求,现在分享给大家。 import com.alibaba.fastjson.seriali...

流水随清风的博客 1万+

fastjson-对象转json字符串时保留空字段SerializerFeature无效的问题

需求简述 将java实体类转换为json字符串,空字段也需要转换。 问题说明 用fastjson将java对象转json字符串时默认去除空字段,网上查阅一番,都说转的时候添加SerializerFeature.WriteNullStringAsEmpty参数就行,亲测了一下,没有达到效果(原因未知)。 如下例子:AssessReq 还有个caseId字段特意不设置值 AssessReq ar= new AssessReq(); ar.setAge(11); ar.setUsername("test"); l

qq_21758475的博客 5175

Springboot 2.x fastJson 返回json数据中null字段不显示解决方法

使用 fastJson 返回json数据前端时候,value为null 时,字段名会被fastJson 自动过滤 记录一下值为null不过滤的几种办法: 实体类中字段加上对应注解 @JSONField(serialzeFeatures= {SerializerFeature.WriteMapNullValue}) private String openId; 在properties...

qq_36174487的博客 1万+

阿里巴巴fastjson转换对象时属性为空null的处理为空串""的解决办法

在使用阿里巴巴的插件返回对象是,如果需要对其进行json格式化一下,默认是不反回null属性的,当然可以设置的,使用重载方法 JSONObject.toJSONString(travelWrite1, SerializerFeature.WriteMapNullValue 注意是使用SerializerFeature.WriteMapNullValue序列化规则 这里介绍一下JSONObj...

长草颜团子 12万+

fastJSON对象转json字符串时遇到null让其转为空串““

创建一个学生对象 public class Student { private String name; private int age; private String gender; public Student() { } public Student(String name, int age, String gender) { this.name = name; this.age = age; this.gender = gender; } public S

# Never Give up & 1432

fastjson判空_fastjson JSON 对象为空保留null

fastjson,对象转json字符串的过程中对value为null的值的一些处理前言 fastjson是一个非常好用的java库,用于操作对象json序列化等等. 问题 最近在写代码的时候遇到问题,通过JSON.toJSONString方法将一个实体对象转为json字符串,转出来 ...json对象和java对象的相互转换方法&lpar;json-lib、jackson、fastjson...

weixin_39662142的博客 1178

fastJson配置的(FastJsonConfiguration)的作用 null装换成““ 或者是不返回null值

实际开发过程中,当我们返回json数据时,如果数据为空,那么默认返回null(因为ResponseBody这个注解底层就是使用的jackson)。毕竟程序员不喜欢null这个字眼。 那么我们如何不让他返回null呢?我们可以使用fastJson解决。fastJson是阿里巴巴的开源库,被誉为史上最快的Json解析库 参考博客1 参考博客2 参考博客3 参考博客4 这辈子坚持与不坚持都不可怕,怕的是独自走在坚持的道路上!!! ...

taiguolaotu的博客 5183

解决fastjson不输出空字符串、null/设置显示fastjson空值也显示

问题重现 首先新建一个map向里面put key和value Map < String , Object > testMap= new HashMap< String , Object>(16); testMap.put("test1","value1"); testMap.put("test2","value2"); testMap.put("test3",null); String testStr = JSON

银魄清辉自夜凝的博客 1万+
上一篇: Linux CenterOS7 安装配置java运行环境(JDK、mysql、tomcat)
下一篇: Linux CentOS 下Nginx安装
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值