前言

当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后可以解决。


总结

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

在这里插入图片描述

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐