让JSONObject 转换时保留为null的字段

package com.tsvv.test;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class Test0622 {
    
    public static void main(String[] args) {
        String text = "此处省略业务JSON";
        JSONObject json = JSONObject.parseObject(text);
        JSONObject userIdAndCodeJSON = (JSONObject)json.get("userIdAndCodeJSON");
        userIdAndCodeJSON.put("userId", null);
        String result = JSONObject.toJSONString(userIdAndCodeJSON, SerializerFeature.WriteMapNullValue);
        System.out.println(result);
    }

}

 直接转换时结果为:{"flag":"0","userCode":"user222"};

 用

JSONObject.toJSONString(JSONObject对象 , SerializerFeature.WriteMapNullValue);

转换时结果为:{"flag":"0","userCode":"user222","userId":null}

原文地址:https://www.cnblogs.com/tsvv-plus/p/14919380.html