首页 > 解决方案 > 将 JSONArray 从 java 发送到 nodeJS 会出现语法错误,这是为什么呢?

问题描述

我正在尝试将 jsonArray 从我的 javacode 发送到我的 nodeJS 应用程序,但我在 nodejs 端不断收到此错误,我无法理解这是为什么?发送一个普通的 JSONObject 可以正常工作。任何帮助将不胜感激!

SyntaxError: Unexpected token C in JSON at position 1
at JSON.parse (<anonymous>)
at parse (E:\Visual code projects\NodeJS\node_modules\body-parser\lib\types\json.js:89:19)
at E:\Visual code projects\NodeJS\node_modules\body-parser\lib\read.js:121:18
at invokeCallback (E:\Visual code projects\NodeJS\node_modules\raw-body\index.js:224:16)
at done (E:\Visual code projects\NodeJS\node_modules\raw-body\index.js:213:7)
at IncomingMessage.onEnd (E:\Visual code projects\NodeJS\node_modules\raw-body\index.js:273:7)
at IncomingMessage.emit (events.js:387:35)
at endReadableNT (internal/streams/readable.js:1317:12)
at processTicksAndRejections (internal/process/task_queues.js:82:21)

我发送到 nodeJS 应用程序的 json 数组如下所示:

[Candlestick[openTime=1629028800000,open=45923.57000000,high=46070.00000000,low=45700.44000000,close=45808.00000000,volume=1372.55048700,closeTime=1629032399999,quoteAssetVolume=62946206.41606293,numberOfTrades=42003,takerBuyBaseAssetVolume=699.78407800,takerBuyQuoteAssetVolume=32095106.77383602],
Candlestick[openTime=1629032400000,open=45808.00000000,high=46070.00000000,low=45500.00000000,close=46050.00000000,volume=1911.24599100,closeTime=1629035999999,quoteAssetVolume=87529798.03243646,numberOfTrades=53351,takerBuyBaseAssetVolume=905.77985600,takerBuyQuoteAssetVolume=41495114.05028976],
Candlestick[openTime=1629036000000,open=46049.99000000,high=46498.89000000,low=45759.91000000,close=45862.84000000,volume=2612.72490800,closeTime=1629039599999,quoteAssetVolume=120720724.93845534,numberOfTrades=67231,takerBuyBaseAssetVolume=1326.32927300,takerBuyQuoteAssetVolume=61298610.46515451],
Candlestick[openTime=1629039600000,open=45862.84000000,high=46199.50000000,low=45810.73000000,close=46167.90000000,volume=1398.39949000,closeTime=1629043199999,quoteAssetVolume=64323828.51794621,numberOfTrades=40297,takerBuyBaseAssetVolume=745.55851400,takerBuyQuoteAssetVolume=34296263.66869613]]

这是我的 java 代码,我从 api 获取烛台数据,然后将其转换为 json 数组。然后将 jsonarray 发布到我的 nodejs 端点。

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;

public class HttpPostToNode {

public JSONArray convertCandleToJSON(List<Candlestick> candlesticks) {
    JSONArray jsonArray = new JSONArray();
    for (Candlestick candlestick : candlesticks) {
        jsonArray.add(candlestick);
    }
    System.out.println(jsonArray.toJSONString());
    return jsonArray;
}

public void post(String uri, String data) throws Exception {
    HttpClient client = HttpClient.newBuilder().build();
    HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(uri))
            .header("Content-Type", "application/json")   //Must be this content type to post JSON to nodejs
            .POST(HttpRequest.BodyPublishers.ofString(data))
            .build();

    HttpResponse<?> response = client.send(request, HttpResponse.BodyHandlers.discarding());
    System.out.println(response.statusCode());
}


public static void main(String[] args) throws Exception {
    HttpPostToNode httpost = new HttpPostToNode();
    DownloadCandles d = new DownloadCandles(TimeStamps.monthAgo(), "BTCUSDT");
    d.asyncGetCandles();
    
    
    while (!d.downloadReady) {
        Thread.sleep(50);
    }

    if (d.downloadReady) {
        System.out.println("Download ready");
    }
    
    JSONArray jsonArray = httpost.convertCandleToJSON(d.candles);
    httpost.post(AlgoConstants.API_END_POINT_CANDLESTICK, jsonArray.toJSONString());
      }
   }

我的nodejs代码:

var port = 8080;
const { json } = require('body-parser');
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 = JSON.parse(req.body);
    console.log(jsonArray);      
})

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

标签: javascriptjavanode.jsjsonexpress

解决方案


Json 无效。

  1. 它应该被包装为一个对象
  2. 钥匙必须用双层包装
  3. 键在同一对象中出现的次数不能超过一次。
  4. =符号在 json 中无效,你必须用:

我在这里修复了json:

{
    "Candlestick": [
        {
            "openTime": 1629028800000,
            "open": 45923.57,
            "high": 46070.0,
            "low": 45700.44,
            "close": 45808.0,
            "volume": 1372.550487,
            "closeTime": 1629032399999,
            "quoteAssetVolume": 62946206.41606293,
            "numberOfTrades": 42003,
            "takerBuyBaseAssetVolume": 699.784078,
            "takerBuyQuoteAssetVolume": 32095106.77383602
        },
        {
            "openTime": 1629032400000,
            "open": 45808.0,
            "high": 46070.0,
            "low": 45500.0,
            "close": 46050.0,
            "volume": 1911.245991,
            "closeTime": 1629035999999,
            "quoteAssetVolume": 87529798.03243646,
            "numberOfTrades": 53351,
            "takerBuyBaseAssetVolume": 905.779856,
            "takerBuyQuoteAssetVolume": 41495114.05028976
        },
        {
            "openTime": 1629036000000,
            "open": 46049.99,
            "high": 46498.89,
            "low": 45759.91,
            "close": 45862.84,
            "volume": 2612.724908,
            "closeTime": 1629039599999,
            "quoteAssetVolume": 120720724.93845535,
            "numberOfTrades": 67231,
            "takerBuyBaseAssetVolume": 1326.329273,
            "takerBuyQuoteAssetVolume": 61298610.46515451
        },
        {
            "openTime": 1629039600000,
            "open": 45862.84,
            "high": 46199.5,
            "low": 45810.73,
            "close": 46167.9,
            "volume": 1398.39949,
            "closeTime": 1629043199999,
            "quoteAssetVolume": 64323828.51794621,
            "numberOfTrades": 40297,
            "takerBuyBaseAssetVolume": 745.558514,
            "takerBuyQuoteAssetVolume": 34296263.66869613
        }
    ]
}

尝试使用有效的 json

Java端解决方案

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
 * The type Http post to node.
 */
public class HttpPostToNode {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * Convert candle to json string.
     *
     * @param candlesticks the candlesticks
     * @return the string
     * @throws JsonProcessingException the json processing exception
     */
    public String convertCandleToJSON(List<Candlestick> candlesticks) throws JsonProcessingException {
        return objectMapper.writeValueAsString(candlesticks);
    }

    /**
     * Post.
     *
     * @param uri  the uri
     * @param data the data
     * @throws Exception the exception
     */
    public void post(String uri, String data) throws Exception {
        HttpClient client = HttpClient.newBuilder().build();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(uri))
                .header("Content-Type", "application/json")   //Must be this content type to post JSON to nodejs
                .POST(HttpRequest.BodyPublishers.ofString(data))
                .build();

        HttpResponse<?> response = client.send(request, HttpResponse.BodyHandlers.discarding());
        System.out.println(response.statusCode());
    }


    /**
     * The entry point of application.
     *
     * @param args the input arguments
     * @throws Exception the exception
     */
    public static void main(String[] args) throws Exception {
        HttpPostToNode httpost = new HttpPostToNode();
        DownloadCandles d = new DownloadCandles(TimeStamps.monthAgo(), "BTCUSDT");
        d.asyncGetCandles();

        while (!d.downloadReady) { // Improve this while wih retryable method
            Thread.sleep(50);
        }

        System.out.println("Download ready");
        String json = httpost.convertCandleToJSON(d.candles);
        httpost.post(AlgoConstants.API_END_POINT_CANDLESTICK,json);
    }
}

推荐阅读