简体   繁体   中英

Parsing JSON Array with BodyParser in Node.js

Hi where to convert a json using node.js, to do it using body-parser with the code entered below: I am generated the error below. What is this error due to? how can I solve it? At the bottom I added the front-end java code for sending the json! The strange thing is that the -Note- field is not displayed in the request.body

Error --> console.log(request.body):

'{"Articoli":':
   { '{"Codice":"VAS-100","Descrizione":"SCHEDA DI ANALISI AD 1 INGRESSO \/ 1 USCITA ALLARME","Prezzo":"35.0"}': '' } }

Error  SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)

Node.js:

    const express = require("express");
    const myParser = require("body-parser");
    const http = require('http');
    const app = express(); 

    app.use(myParser.json());
    app.use(myParser.urlencoded({ extended: true }));
    //port
    const RunPort=8989;
    //server run on port
    app.listen(RunPort, function () {
        console.log("Server run on Port: ",RunPort);
    })

app.post("/rapportini/generarapportino", async function (request, response) {

    try {
        console.log(request.body);
        var data = JSON.parse(Object.keys(request.body)[0]);
        const ret = await RapportiniController.GeneraRapportino(data.Note);
        response.setHeader('Content-Type', 'application/json');
        response.send(JSON.stringify({
            return: ret
        }));
    } catch (err) {
        console.log("Error ", err)
    }
});

JSON:

  {
    "Note": "some note",
    "Articoli":[{
                    "Codice": "CodiceValue 1",
                    "Descrizione": "DescrizioneValue 1",
                    "Presso": "Prezzo 1"
                },
                {
                    "Codice": "CodiceValue 2",
                    "Descrizione": "DescrizioneValue 2",
                    "Presso": "Prezzo 2"
                }]
    }

Front-End Java Code(Android):

Generate JSON:

 String ret = "";
        try {
            JSONObject obj = new JSONObject();
            obj.put("Note", note);
            JSONArray objarticoli = new JSONArray();
            int size = articoli.size();
            int i = 0;
            System.out.println("\n Size of articoli: " + size);

            for (i = 0; i <
                    size; i++) {

                JSONObject artItem = new JSONObject();
                artItem.put("Codice", articoli.get(i).GetCodice().toString());
                artItem.put("Descrizione", articoli.get(i).GetDescrizione().toString());
                artItem.put("Prezzo", articoli.get(i).GetPrezzo().toString());
                objarticoli.put(artItem);
            }

            obj.put("Articoli", objarticoli);

            try {
                Database db = new Database();
                ret = db.RequestArray("/rapportini/generarapportino", obj, true);
            } catch (Exception ex) {
                System.out.println("\n Errore login Model");
            }

        } catch (Exception ex) {
            ErrorManagement.SendError("Errore: Generazione Rapportino: " + ex);
        }
        return ret;

Send of JSON:

String response = "";
        System.out.println("\n Sono in GetResponse con JSONOject: "+object);
        try {
            URL url = new URL("/rapportini/generarapportino");
            byte[] postDataBytes = object.toString().getBytes("UTF-8");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
            conn.setDoOutput(true);
            conn.getOutputStream().write(postDataBytes);
            Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            StringBuilder sb = new StringBuilder();
            for (int c; (c = in.read()) >= 0; ) {
                sb.append((char) c);
            }
            response = sb.toString();
        } catch (Exception ex) {
            System.out.println("\n Errore funzione GetResponse class JSONRequest: "+ex);
        }
        return response;

First Use JSON.stringify then parse it to get desired output

var req={ '{"Articoli":': { '{"Codice":"KSI4101000.300","Descrizione":"gemino Bus Scheda GSM\/GPRS (solo PCBA) solo per KS-BUS","Prezzo":"163.35"}': '' } }

var data = JSON.parse(JSON.stringify(req));

You need to set correct Content-Type in Android application that is application/json

conn.setRequestProperty("Content-Type", "application/json");

and then accept in NodeJS application

app.post("/rapportini/generarapportino", async function (request, response) {

    try {
        const ret = await RapportiniController.GeneraRapportino(request.body.Note);
        response.json({
            return: ret
        });
    } catch (err) {
        console.log("Error ", err)
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM