JSONObject解析数据库Date类型报错问题

博客讲述了在处理数据库查询结果转化为JSON时遇到的java.sql.Date类型转换异常。问题源于java.util.Date和java.sql.Date之间的转换。解决方案是通过JsonConfig注册java.sql.Date的JsonValueProcessor,将其格式化为字符串。修改后的代码将查询结果先存入Map,再应用JsonConfig进行转换,避免了直接转换的错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JSONObject解析数据库Date类型报错问题

最近项目在写服务器后端查询空间数据的接口时,由于表结构不一致,直接写了一个通用函数用json储存数据库中查询的结果,然而今天前端查询一个表的时候无法查到相应的结果,查了一下代码发现爆了如下错误。

报错:

Caused by: java.lang.IllegalArgumentException
at java.sql.Date.getHours

原因是该表中存在Date类型的字段,由于java.util.Date 和 java.sql.Date的转换问题造成的。

解决方案:采用JsonConfig注册对应的Date类型java.sql.Date;

将ResultSet结果存入json,原代码如下:

public JSONArray resultSetToJson(ResultSet rs)
    {
        // json数组
        JSONArray array = new JSONArray();
        // 获取列数
        ResultSetMetaData metaData = null;
        try {
            metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();
            // 遍历ResultSet中的每条数据
            while (rs.next()) {
                JSONObject jsonObj = new JSONObject();
                // 遍历每一列
                for (int i = 1; i <= columnCount; i++) {
                    String columnName = metaData.getColumnLabel(i);
                    Object value = rs.getObject(columnName);
                    jsonObj.put(columnName, value);
                }
                array.add(jsonObj);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return array;
    }

为了解决上述问题,通过定义配置文件,并且注册时间类型:

JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonValueProcessor(java.sql.Date.class, new JsonValueProcessor() {
      final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
      @Override
      public Object processArrayValue(Object o, JsonConfig jsonConfig) {
        return null;
      }

      @Override
      public Object processObjectValue(String s, Object o, JsonConfig jsonConfig) {
        if (o != null) {
          return simpleDateFormat.format(o);
        } else {
          return null;
        }
      }
});			

将jsonConfig应用在JSONObject时候,需要用到JSONObject.fromObject(),例如:

JSONObject js = JSONObject.fromObject(jsonStr,jsonConfig)

但是本例中是直接将ResultSet获取到的结果存入JSONObject,所以采用先将结果放入Map对象中,再放到json里面:

Map<String,Object> map = new HashMap<>();
map.put(columnName, value);
jsonObj.putAll(map,jsonConfig);

查到的结果如下:

在这里插入图片描述

改完收工!

报错信息Content-Length: 476 Connection: keep-alive Content-Type: application/json; charset=utf-8 Date: Tue, 11 Mar 2025 07:11:15 GMT Server: Microsoft-HTTPAPI/2.0 Strict-Transport-Securi"..."c\u56e0\u4e3a\u89c6\u56fe DimAttributeProjTable \u7684\u8868 ProjTable \u4e2d\u4e0d\u5b58\u5728\u8bb0\u5f55\u3002","Level":"Error"}] Server-Timing: total;dur=567.0874 Content-Security-Policy: frame- 2025-03-11 15:11:15,640 ERROR A2 - [null] WeaverHttp&HS2249&15:11:08&/workflow/request/RequestOperation.jsp-295158[weaverHAN.action.D365PersonalExpenseAccountP.D365PersonalExpenseAccountP:146] - weaverHAN.action.D365PersonalExpenseAccountP.D365PersonalExpenseAccountP net.sf.json.JSONException: A JSONObject text must begin with '{' at character 1 of rror when reading response headers: small read buffer. Increase ReadBufferSize. Buffer size=4096, contents: "HTTP/1.1 200 OK Content-Length: 476 Connection: keep-alive Content-Type: application/json; charset=utf-8 Date: Tue, 11 Mar 2025 07:11:15 GMT Server: Microsoft-HTTPAPI/2.0 Strict-Transport-Securi"..."c\u56e0\u4e3a\u89c6\u56fe DimAttributeProjTable \u7684\u8868 ProjTable \u4e2d\u4e0d\u5b58\u5728\u8bb0\u5f55\u3002","Level":"Error"}] Server-Timing: total;dur=567.0874 Content-Security-Policy: frame- at net.sf.json.util.JSONTokener.syntaxError(JSONTokener.java:512) at net.sf.json.JSONObject._fromJSONTokener(JSONObject.java:901) at net.sf.json.JSONObject._fromString(JSONObject.java:1122) at net.sf.json.JSONObject.fromObject(JSONObject.java:174) at net.sf.json.JSONObject.fromObject(JSONObject.java:148) at
最新发布
03-12
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值