You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java向NodeJS发送JSONArray报JSON语法错误的原因是什么?

问题根因
  • Java侧序列化逻辑错误:你往JSONArray中添加自定义Candlestick对象时,JSON库没有正确序列化该对象,直接调用了它的默认toString()方法,生成了Candlestick[openTime=xxx]这种非JSON格式的字符串,而非符合JSON规范的{"openTime": xxx, "open": xxx}结构。你之前发送普通JSONObject运行正常,是因为当时构造的JSONObject本身就是合法的键值对结构,序列化后符合JSON规范。你贴的请求体第二个字符就是C,刚好对应报错信息里的Unexpected token C in JSON at position 1。
  • Node.js侧重复解析:你已经配置了app.use(express.json({limit:'1mb'}))中间件,它会自动识别application/json类型的请求,把请求体解析为JS对象挂载到req.body上,不需要再手动调用JSON.parse(req.body),对已经是对象的内容执行解析也会触发报错。
修复方案

Java侧修改

把Candlestick对象转换为合法的JSONObject后再加入数组,参考修改后的代码:

public JSONArray convertCandleToJSON(List<Candlestick> candlesticks) {
    JSONArray jsonArray = new JSONArray();
    for (Candlestick candlestick : candlesticks) {
        // 方案1:如果使用fastjson等支持自动序列化的库,直接转JSON对象
        JSONObject candleJson = (JSONObject) JSON.toJSON(candlestick);
        // 方案2:如果JSON库不支持自动序列化,手动映射属性
        // JSONObject candleJson = new JSONObject();
        // candleJson.put("openTime", candlestick.getOpenTime());
        // candleJson.put("open", candlestick.getOpen());
        // 其余属性依次调用get方法赋值
        jsonArray.add(candleJson);
    }
    // 先确认输出的字符串是[{"openTime":xxx,...},...]的合法格式,再发请求
    System.out.println(jsonArray.toJSONString());
    return jsonArray;
}

Node.js侧修改

移除手动解析逻辑,直接使用req.body即可,同时补充请求响应避免超时:

var port = 8080;
const express = require('express'); 
const app = express();
app.use(express.static('public'));
app.use(express.json({limit:'1mb'})); 

app.post('/API', (req, res) => {
    const jsonArray = req.body;
    console.log(jsonArray);
    res.sendStatus(200);
})

app.listen(port, () => {
    console.log('Server is up on port '+port)
})

内容的提问来源于stack exchange,提问作者leroyv

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 18:27:02