Home > Enterprise >  Sending JSONArray from java to nodeJS gives syntax error, why is this?
Sending JSONArray from java to nodeJS gives syntax error, why is this?

Time:09-16

I am trying to send a jsonArray from my javacode to my nodeJS application, but i keep getting this error on my nodejs side, which i have trouble understanding why this is? As sending a normal JSONObject works fine. Any help would be greatly appreciated!

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)

The json array i am sending to the nodeJS app looks like this:

[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]]

This is my java code where i get candlestick data from an api and then convert it to a json array. And then post the jsonarray to my nodejs endpoint.

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());
      }
   }

My nodejs code:

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)
    })

CodePudding user response:

Json is invalid.

  1. It should be wrapped as an object
  2. keys have to be wrapped with double quetes
  3. key cannot appeared more then one occurrence in same object.
  4. = symbol not valid in json and you have to to separate between key and value with :

I have fixed the json down here:

{
    "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
        }
    ]
}

Try to work with valid json

Java side solution

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);
    }
}
  • Related