Node.js解析来自iOS URLSession主体的JSON
使用Node.js解析来自iOS URLSession主体的JSON,ios,json,node.js,swift,Ios,Json,Node.js,Swift,使用URLSession从iOS设备发送JSON。我发送: let body = try? JSONSerialization.data(withJSONObject: order.toJSON()) // { "customer": 123 } request.httpBody = body request.httpMethod = "POST" URLSession.shared.dataTask(with: request) { (data, response, error) in
URLSession
从iOS设备发送JSON。我发送:
let body = try? JSONSerialization.data(withJSONObject: order.toJSON())
// { "customer": 123 }
request.httpBody = body
request.httpMethod = "POST"
URLSession.shared.dataTask(with: request) { (data, response, error) in
...
}.resume()
如果在此之后打印正文,我会得到一个有效的JSON:
print(String(data: request.httpBody!, encoding: .utf8)!)
// {"customer":123}
然后,在服务器端的nodejs中,我有以下代码(node或javascript不是我的主域):
我的问题是,为什么要将原始JSON添加到JSON键中,如何避免
使用JSON.parse
不起作用,因为它得到了一个漏洞,JSON是一个空值的键(如示例所示) 您在那里使用的toJSON()
方法是什么?在我看来,你要把它串起来两次,出于某种原因,这个方法正在把它包装到字典中
以下是一个完整的、有效的操场片段:
import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
let url = URL(string: "http://requestb.in/<<your-requestbin-key>>")
var request = URLRequest(url: url!)
let order = ["customer": 123]
let body = try? JSONSerialization.data(withJSONObject: order)
request.httpBody = body
request.httpMethod = "POST"
URLSession.shared.dataTask(with: request) { (data, response, error) in
print(response!)
}.resume()
导入UIKit
导入PlaygroundSupport
PlaygroundPage.current.NeedsDefiniteExecution=true
让url=url(字符串:http://requestb.in/")
var request=URLRequest(url:url!)
让订单=[“客户”:123]
让身体=尝试?JSONSerialization.data(带jsonObject:order)
request.httpBody=body
request.httpMethod=“POST”
URLSession.shared.dataTask(带:请求){(数据、响应、错误)在
打印(响应!)
}1.简历()
请注意,无需在任何地方调用toJSON()
(这也不是内置的Swift方法)
请求B.在其答复中:
抱歉,我不太清楚toJSON()
是一个自定义方法,返回一个[String:Any]
字典。我会看一下你的代码片段,并尝试直接复制硬编码dict,谢谢,看起来这就是问题所在。您已经通过JSONSerialization.data()
对请求正文进行了字符串化。不需要做两次。
import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
let url = URL(string: "http://requestb.in/<<your-requestbin-key>>")
var request = URLRequest(url: url!)
let order = ["customer": 123]
let body = try? JSONSerialization.data(withJSONObject: order)
request.httpBody = body
request.httpMethod = "POST"
URLSession.shared.dataTask(with: request) { (data, response, error) in
print(response!)
}.resume()