在 Node.js 中使用 BodyParser 解析 JSON 数组



嗨,在哪里使用 node.js 转换 json,使用正文解析器进行,输入的代码如下: 我在下面生成了错误。此错误是由于什么引起的?我该如何解决?在底部,我添加了用于发送 json 的前端 java 代码!奇怪的是,-Note- 字段没有显示在 request.body 中

错误 -->控制台.log(请求正文(:

'{"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>)

节点.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)
}
});

杰森:

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

前端Java代码(安卓(:

生成 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;

发送 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;

首先使用 JSON.stringify,然后解析它以获得所需的输出

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

您需要在Android应用程序中设置正确的Content-Typeapplication/json

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

然后在 NodeJS 应用程序中接受

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

最新更新