JSON.toJSONString(jsonObject),出现 “$ref“ 解决方案

本文介绍了在使用Fastjson时,遇到对象中有两个值相同会生成$ref引用的问题,展示了如何通过SerializerFeature.WriteMapNullValue特性去除$ref,以及在升级到Fastjson2版本后问题的自动解决。

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


前言

当json对象中有2个对象的值一样时,会出现 $ref ,来引用相同的值,这时去解析字符串时可能会有些问题,需要把引用去掉。


提示:以下是本篇文章正文内容,下面案例可供参考

一、问题复现

String jsonStr = "{\"rowIndex\":6,\"rowCount\":6}";
JSONObject jsonObject = JSON.parseObject(jsonStr);
System.out.println(jsonObject);
System.out.println(JSON.toJSONString(jsonObject));

// 打印的值如下
{"rowIndex":6,"rowCount":6}
{"rowIndex":6,"rowCount":{"$ref":"rowIndex"}}

二、解决方案

使用:SerializerFeature.WriteMapNullValue.getMask()

JSON.toJSONString(jsonObject, SerializerFeature.WriteMapNullValue.getMask())

String jsonStr = "{\"rowIndex\":6,\"rowCount\":6}";
JSONObject jsonObject = JSON.parseObject(jsonStr);
System.out.println(jsonObject);
System.out.println(JSON.toJSONString(jsonObject));
System.out.println(JSON.toJSONString(jsonObject, SerializerFeature.WriteMapNullValue.getMask()));

// 打印的值如下
{"rowIndex":6,"rowCount":6}
{"rowIndex":6,"rowCount":{"$ref":"rowIndex"}}
{"rowIndex":6,"rowCount":6}

注:以上场景出现$ref是使用了fastjson中出现,当使用fastjson2后可以解决。


总结

我恋的不是雪,而是有你的冬天;雪景虽美,但我的眼中却只有你。

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值