使用fastjson转json字符串时值为null的字段丢失
fastjson
FASTJSON 2.0.x has been released, faster and more secure, recommend you upgrade.
项目地址:https://gitcode.com/gh_mirrors/fastj/fastjson
免费下载资源
·
记一次使用fastjson转字符串出现的问题
@Transactional(rollbackFor = Exception.class)
public ResultEnum add(Map<String, String> addMap) {
....................
List<Map<String, Object>> raw_list = parseJson(userid);
Map<String, Object> new_Cus = new HashMap<>();
new_Cus.put(KEY_ID, (raw_list.size() + 1) + "");
new_Cus.put(KEY_NAME, addMap.get(KEY_NAME));
new_Cus.put(KEY_DISPLAY, addMap.get(KEY_DISPLAY));
new_Cus.put(KEY_STATE, "1");
new_Cus.put(KEY_AIDS, null);
raw_list.add(new_Cus);
String jsonStr = JSON.toJSONString(raw_list);
........................
}
如上,在将rawList转为json字符串的时候,发现aids字段丢失了
解决:
这里需要给toJSONString方法添加SerializerFeature属性
SerializerFeature属性的枚举类如下:
值 | 说明 |
---|---|
QuoteFieldNames | 输出key时是否使用双引号,默认为true |
WriteMapNullValue | 是否输出值为null的字段,默认为false |
WriteNullNumberAsZero | 数值字段如果为null,输出为0,而非null |
WriteNullListAsEmpty | List字段如果为null,输出为[],而非null |
WriteNullStringAsEmpty | 字符类型字段如果为null,输出为"",而非null |
WriteNullBooleanAsFalse | Boolean字段如果为null,输出为false,而非null |
修改后:
/**
* 添加分类
* @param addMap
* @return
*/
@Transactional(rollbackFor = Exception.class)
public ResultEnum add(Map<String, String> addMap) {
.............
List<Map<String, Object>> raw_list = parseJson(userid);
......
Map<String, Object> new_Cus = new HashMap<>();
new_Cus.put(KEY_ID, (raw_list.size() + 1) + "");
new_Cus.put(KEY_NAME, addMap.get(KEY_NAME));
new_Cus.put(KEY_DISPLAY, addMap.get(KEY_DISPLAY));
new_Cus.put(KEY_STATE, "1");
List<String> aids = new ArrayList<>();
new_Cus.put(KEY_AIDS, aids);
raw_list.add(new_Cus);
/*
WriteMapNullValue:是否输出值为null的字段,默认为false
WriteNullListAsEmpty:List字段如果为null,输出为[],而非null
*/
String jsonStr = JSON.toJSONString(raw_list, SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullListAsEmpty);
...................
}
这时再转为json,aids字段存在且为[]
更多属性瞅这儿:
https://blog.csdn.net/liu_shi_jun/article/details/90453907#_5
GitHub 加速计划 / fastj / fastjson
25.69 K
6.51 K
下载
FASTJSON 2.0.x has been released, faster and more secure, recommend you upgrade.
最近提交(Master分支:3 个月前 )
c942c834 - 1 年前
5bc4709b - 1 年前
更多推荐
已为社区贡献1条内容
所有评论(0)