从Swift发送到Node.js的JSON无效

时间:2018-05-28 08:40:55

标签: json node.js swift

我必须向javascript node.js服务器发送一个swift结构,所讨论的结构包含一个字符串字段和一个ItemStruct类型的数组!下面我把json文本!现在我意识到问题在于json格式不正确我的问题是如何解决这个问题?

从服务器打印JSON:

    { '{\n  "Note" : "Sac",\n  "Articoli" : ':
   { '\n    {\n      "Fornitore" : "COMET",\n      "Prezzo" : 48.850000000000001,\n      "CodArt" : "GW.2000",\n      "Importato" : "COMET",\n      "PrezzoListino" : 58.149999999999999,\n      "IdArticolo" : 8013,\n      "CodMarca" : "ARE",\n      "Descrizione" : "LANTERNA RICARICABILE NEW LED"\n    }\n  ': '' } }

Swift代码:

struct ArticoloStruct: Codable {

       var IdArticolo: Int
       var CodArt: String!
       var CodMarca: String!
       var Descrizione: String!
       var Prezzo: Double!
       var PrezzoListino: Double!
       var CodiceValuta: String!
       var Fornitore: String!
       var Importato: String!
}

struct RapportinoStruct: Codable {        
  var Note:String
  var Articoli:[ArticoloStruct]
}

class RapportiniModel {
static let lock = NSLock()

init() {

}

func GeneraRapportino(Note: String, Articoli: [ArticoloStruct], completion: @escaping (String) -> ())
{
    RapportiniModel.lock.lock()

    let db = Database()
    let value=RapportinoStruct(Note: Note, Articoli: Articoli)
    let encoder = JSONEncoder()
    encoder.outputFormatting = .prettyPrinted
    let jsonData = try! encoder.encode(value)
    print("JSON Value: \(jsonData)")
    var request = URLRequest(url: URL(string: db.GetServerURL() + "/rapportini/generarapportino")!)
    request.httpMethod = "POST"
    request.httpBody = jsonData
    print("\n Body Request: \(request.httpBody)")
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {
            print(error?.localizedDescription ?? "No data")
            completion("false")
            return
        }
        let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
        if let responseJSON = responseJSON as? [String: Any] {
            let read = responseJSON["return"]!
            completion(read as! String)
        }

    }
    task.resume()

    print("Fine")
    RapportiniModel.lock.unlock()
}

}

Node.js:代码:

app.post("/rapportini/generarapportino",async function(request,response)
{
    console.log("\n Qualcuno sta generando un rapportino");
    try
    {
        console.log(request.body);
        var data = JSON.parse(Object.keys(request.body)[0]);
        console.log("\n Data: ",data);
        const ret=await RapportiniController.GeneraRapportino(data.Note);
        response.setHeader('Content-Type', 'application/json');
        response.send(JSON.stringify({ return: ret }));
    }

    catch(err){
        console.log("Errore generazione rapportino ",err)
    }

});

Node.js错误:

SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at /Users/riccardo/Desktop/Myapp/src/ServerJS/ServerJS/Router/Rapportini.js:14:25
    at Layer.handle [as handle_request] (/Users/riccardo/Desktop/Myapp/src/ServerJS/ServerJS/node_modules/express/lib/router/layer.js:95:5)

使用swift的正文请求:

335 bytes

1 个答案:

答案 0 :(得分:1)

替换此代码

let jsonData = try? JSONEncoder().encode(value)

let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let jsonData = try? encoder.encode(value)