FastJson系列化使用toJSONString时null值标题

鼠扑  论坛元老 | 2025-2-15 06:12:47 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 1070|帖子 1070|积分 3210

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
标题描述

在使用fastjson调用
  1. JSON.toJSONString(JSON.parseObject(demo), features);
复制代码
fastJson包版本
  1.   <dependency>
  2.             <groupId>com.alibaba</groupId>
  3.             <artifactId>fastjson</artifactId>
  4.             <version>2.0.53</version>
  5.   </dependency>
复制代码
方法将一个String转换成一个对象时,假如对象obj的属性字段有值为null时,该字段会被系列化成"";
传入String对象:
  1. {
  2.     "code": "SUCCESS",
  3.     "data": {
  4.         "amount_of_handling_fees": null,
  5.         "associate_amount": 200000,
  6.         "associate_currency": "VND",
  7.         "associate_risk_review_id": "",
  8.         "client_rate": "1.0000000000000000",
  9.         "credited_amount": null,
  10.         "fx_order_no": "",
  11.         "goods_tax": null,
  12.         "incoming_payment_id": "SZLS2025021011112568049767730",
  13.         "merchant_order_list": [
  14.             {
  15.                 "merchant_order_no": "1889223743019364353",
  16.                 "order_associate_amount": 200000,
  17.                 "order_associate_amount_goods": null,
  18.                 "order_associate_amount_service": null,
  19.                 "order_currency": "VND",
  20.                 "order_goods_tax": null,
  21.                 "order_service_tax": null,
  22.                 "trade_order_no": "MYDD2025021116124303299021"
  23.             }
  24.         ],
  25.         "order_associated_id": "AS202502111632520283768844",
  26.         "risk_review_remark": "",
  27.         "risk_review_type": "",
  28.         "service_tax": null,
  29.         "status": "processing",
  30.         "tax_amount": null,
  31.         "unsettlement_amount": 200000,
  32.         "unsettlement_currency": "VND"
  33.     },
  34.     "message": "success",
  35.     "timestamp": "2025-02-12T11:16:13+08:00"
  36. }
复制代码
使用系列化后
  1. String sortedJson = JSON.toJSONString( parseObject(demo));
复制代码
  1. {
  2.     "code": "SUCCESS",
  3.     "data": {
  4.         "associate_amount": 200000,
  5.         "associate_currency": "VND",
  6.         "associate_risk_review_id": "",
  7.         "client_rate": "1.0000000000000000",
  8.         "fx_order_no": "",
  9.         "incoming_payment_id": "SZLS2025021011112568049767730",
  10.         "merchant_order_list": [
  11.             {
  12.                 "merchant_order_no": "1889223743019364353",
  13.                 "order_associate_amount": 200000,
  14.                 "order_currency": "VND",
  15.                 "trade_order_no": "MYDD2025021116124303299021"
  16.             }
  17.         ],
  18.         "order_associated_id": "AS202502111632520283768844",
  19.         "risk_review_remark": "",
  20.         "risk_review_type": "",
  21.         "status": "processing",
  22.         "unsettlement_amount": 200000,
  23.         "unsettlement_currency": "VND"
  24.     },
  25.     "message": "success",
  26.     "timestamp": "2025-02-12T11:16:13+08:00"
  27. }
复制代码
标题描述:
我们可以很明显的看到系列化后null已经修改成""
标题分析

其实fastjson的toJSONString()。
源码分析:
com.alibaba.fastjson.JSON
  1. public static String toJSONString(Object object) {
  2.         JSONWriter.Context context = createWriteContext(SerializeConfig.global, DEFAULT_GENERATE_FEATURE);
  3.         try (JSONWriter writer = JSONWriter.of(context)) {
  4.             if (object == null) {
  5.                 writer.writeNull();
  6.             } else {
  7.                 writer.setRootObject(object);
  8.                 Class<?> valueClass = object.getClass();
  9.                 ObjectWriter objectWriter = context.getObjectWriter(valueClass, valueClass);
  10.                 objectWriter.write(writer, object, null, null, 0);
  11.             }
  12.             return writer.toString();
  13.         } catch (com.alibaba.fastjson2.JSONException ex) {
  14.             Throwable cause = ex.getCause() != null ? ex.getCause() : ex;
  15.             throw new JSONException(ex.getMessage(), cause);
  16.         } catch (RuntimeException ex) {
  17.             throw new JSONException("toJSONString error", ex);
  18.         }
  19.     }
复制代码
com.alibaba.fastjson.JSON
  1. static {
  2.         int features = 0;
  3.         features |= SerializerFeature.QuoteFieldNames.getMask();
  4.         features |= SerializerFeature.SkipTransientField.getMask();
  5.         features |= SerializerFeature.WriteEnumUsingName.getMask();
  6.         features |= SerializerFeature.SortField.getMask();
  7.         DEFAULT_GENERATE_FEATURE = features;
  8.     }
复制代码
  1. public static JSONWriter.Context createWriteContext(
  2.             SerializeConfig config,
  3.             int featuresValue,
  4.             SerializerFeature... features
  5.     ) {
  6.         for (SerializerFeature feature : features) {
  7.             featuresValue |= feature.mask;
  8.         }
  9.         ObjectWriterProvider provider = config.getProvider();
  10.         provider.setCompatibleWithFieldName(TypeUtils.compatibleWithFieldName);
  11.         JSONWriter.Context context = new JSONWriter.Context(provider);
  12.         if (config.fieldBased) {
  13.             context.config(JSONWriter.Feature.FieldBased);
  14.         }
  15.         if (config.propertyNamingStrategy != null
  16.                 && config.propertyNamingStrategy != PropertyNamingStrategy.NeverUseThisValueExceptDefaultValue
  17.                 && config.propertyNamingStrategy != PropertyNamingStrategy.CamelCase1x
  18.         ) {
  19.             NameFilter nameFilter = NameFilter.of(config.propertyNamingStrategy);
  20.             configFilter(context, nameFilter);
  21.         }
  22.         if ((featuresValue & SerializerFeature.DisableCircularReferenceDetect.mask) == 0) {
  23.             context.config(JSONWriter.Feature.ReferenceDetection);
  24.         }
  25.         if ((featuresValue & SerializerFeature.UseISO8601DateFormat.mask) != 0) {
  26.             context.setDateFormat("iso8601");
  27.         } else {
  28.             context.setDateFormat("millis");
  29.         }
  30.         if ((featuresValue & SerializerFeature.WriteMapNullValue.mask) != 0) {
  31.             context.config(JSONWriter.Feature.WriteMapNullValue);
  32.         }
  33.         if ((featuresValue & SerializerFeature.WriteNullListAsEmpty.mask) != 0) {
  34.             context.config(JSONWriter.Feature.WriteNullListAsEmpty);
  35.         }
  36.         if ((featuresValue & SerializerFeature.WriteNullStringAsEmpty.mask) != 0) {
  37.             context.config(JSONWriter.Feature.WriteNullStringAsEmpty);
  38.         }
  39.         if ((featuresValue & SerializerFeature.WriteNullNumberAsZero.mask) != 0) {
  40.             context.config(JSONWriter.Feature.WriteNullNumberAsZero);
  41.         }
  42.         if ((featuresValue & SerializerFeature.WriteNullBooleanAsFalse.mask) != 0) {
  43.             context.config(JSONWriter.Feature.WriteNullBooleanAsFalse);
  44.         }
  45.         if ((featuresValue & SerializerFeature.BrowserCompatible.mask) != 0) {
  46.             context.config(JSONWriter.Feature.BrowserCompatible);
  47.             context.config(JSONWriter.Feature.EscapeNoneAscii);
  48.         }
  49.         if ((featuresValue & SerializerFeature.BrowserSecure.mask) != 0) {
  50.             context.config(JSONWriter.Feature.BrowserSecure);
  51.         }
  52.         if ((featuresValue & SerializerFeature.WriteClassName.mask) != 0) {
  53.             context.config(JSONWriter.Feature.WriteClassName);
  54.         }
  55.         if ((featuresValue & SerializerFeature.WriteNonStringValueAsString.mask) != 0) {
  56.             context.config(JSONWriter.Feature.WriteNonStringValueAsString);
  57.         }
  58.         if ((featuresValue & SerializerFeature.WriteEnumUsingToString.mask) != 0) {
  59.             context.config(JSONWriter.Feature.WriteEnumUsingToString);
  60.         }
  61.         if ((featuresValue & SerializerFeature.WriteEnumUsingName.mask) != 0) {
  62.             context.config(JSONWriter.Feature.WriteEnumsUsingName);
  63.         }
  64.         if ((featuresValue & SerializerFeature.NotWriteRootClassName.mask) != 0) {
  65.             context.config(JSONWriter.Feature.NotWriteRootClassName);
  66.         }
  67.         if ((featuresValue & SerializerFeature.IgnoreErrorGetter.mask) != 0) {
  68.             context.config(JSONWriter.Feature.IgnoreErrorGetter);
  69.         }
  70.         if ((featuresValue & SerializerFeature.WriteDateUseDateFormat.mask) != 0) {
  71.             context.setDateFormat(JSON.DEFFAULT_DATE_FORMAT);
  72.         }
  73.         if ((featuresValue & SerializerFeature.BeanToArray.mask) != 0) {
  74.             context.config(JSONWriter.Feature.BeanToArray);
  75.         }
  76.         if ((featuresValue & SerializerFeature.UseSingleQuotes.mask) != 0) {
  77.             context.config(JSONWriter.Feature.UseSingleQuotes);
  78.         }
  79.         if ((featuresValue & SerializerFeature.MapSortField.mask) != 0) {
  80.             context.config(JSONWriter.Feature.MapSortField);
  81.         }
  82.         if ((featuresValue & SerializerFeature.PrettyFormat.mask) != 0) {
  83.             context.config(JSONWriter.Feature.PrettyFormat);
  84.         }
  85.         if ((featuresValue & SerializerFeature.WriteNonStringKeyAsString.mask) != 0) {
  86.             context.config(JSONWriter.Feature.WriteNonStringKeyAsString);
  87.         }
  88.         if ((featuresValue & SerializerFeature.IgnoreNonFieldGetter.mask) != 0) {
  89.             context.config(JSONWriter.Feature.IgnoreNonFieldGetter);
  90.         }
  91.         if ((featuresValue & SerializerFeature.NotWriteDefaultValue.mask) != 0) {
  92.             context.config(JSONWriter.Feature.NotWriteDefaultValue);
  93.         }
  94.         if ((featuresValue & SerializerFeature.WriteBigDecimalAsPlain.mask) != 0) {
  95.             context.config(JSONWriter.Feature.WriteBigDecimalAsPlain);
  96.         }
  97.         if ((featuresValue & SerializerFeature.QuoteFieldNames.mask) == 0
  98.                 && (featuresValue & SerializerFeature.UseSingleQuotes.mask) == 0
  99.         ) {
  100.             context.config(JSONWriter.Feature.UnquoteFieldName);
  101.         }
  102.         if (defaultTimeZone != null && defaultTimeZone != DEFAULT_TIME_ZONE) {
  103.             context.setZoneId(defaultTimeZone.toZoneId());
  104.         }
  105.         context.config(JSONWriter.Feature.WriteByteArrayAsBase64);
  106.         context.config(JSONWriter.Feature.WriteThrowableClassName);
  107.         return context;
  108.     }
复制代码
从源码分析我们可以知道,JSON默认是换成""的
办理方法:

  1.   SerializerFeature[] features = {
  2.                 SerializerFeature.MapSortField,
  3.                 SerializerFeature.WriteMapNullValue
  4.         };
  5. String sortedJson = JSON.toJSONString(JSON.parseObject(demo), features);
复制代码
在使用时,也可以根据自己的需求来添加其他罗列类型,直接在后边添加即可。
最后,希望可以帮助到有必要的码友。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

鼠扑

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表