1、问题描述
在 Java 中使用 net.sf.json.JSONObject.fromObject() 方法将对象转换为 JSONObject 时,如果 Integer 类型的属性值为 null,它会被转换为 0。这是因为 Json-lib 的默认行为对数值类型的空值进行了隐式处理。
2、解决方案
方法 1:配置 JsonConfig 保留 null 值
通过自定义 JsonConfig,明确指定 null 值应保留为 JSON 的 null,而不是默认值:
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.JSONUtils;
public class JsonExample {
public static void main(String[] args) {
YourObject obj = new YourObject(); // 假设 obj 的 Integer 属性为 null
JsonConfig config = new JsonConfig();
// 关键配置:禁用默认值转换
config.setDefaultValueMap(new HashMap());
// 允许 JSON 输出 null 值
JSONUtils.getMorpherRegistry().registerMorpher(new NullDefaultMorpher());
JSONObject jsonObject = JSONObject.fromObject(obj, config);
System.out.println(jsonObject.toString());
}
}
方法 2:升级或更换 JSON 库
Json-lib 已较为陈旧,建议切换到更现代的库(如 Jackson),其对 null 的处理更合理:
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonExample {
public static void main(String[] args) throws Exception {
YourObject obj = new YourObject(); // Integer 属性为 null
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(obj);
System.out.println(json); // 输出 {"intField":null}
}
}
3、总结
Json-lib 的默认行为将 Integer 的 null 转换为 0 是为了兼容基本类型的默认值,但这种设计容易导致数据歧义。通过配置 JsonConfig 或切换至更现代的库(如 Jackson),可以更精确地控制 null 值的序列化行为,确保 JSON 数据的准确性。



2288

被折叠的 条评论
为什么被折叠?



