Java 中使用 net.sf.json.JSONObject.fromObject()踩的坑

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 数据的准确性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值