arrays - Swift JSON“POST”请求数据数组
问题描述
我无法从数据输出中删除数组,尝试使用从数据中获得的引号数量定义一个结构并尝试输入它,但我不能,因为我必须从 JSON 响应中删除数组括号第一的。卡在这里一段时间了,第一次使用 JSON POST 类型。
if let requestUrl = url {
// Prepare URL Request Object
var request = URLRequest(url: requestUrl)
request.httpMethod = "POST"
// HTTP Request Parameters which will be sent in HTTP Request Body
let postString = ["freq": freqId]
// Set HTTP Request Body
request.httpBody = try? JSONSerialization.data(withJSONObject: postString, options: [] );
// Perform HTTP Request
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
// Check for Error
if let error = error {
self.delegate?.didGetError(error: error)
return
}
// Convert HTTP Response Data to a String
if let data = data, let dataString = String(data: data, encoding: .utf8) {
print(dataString)
let quotes = DataModel(quotes: dataString)
self.delegate?.didGetData(data: quotes)
}
}
task.resume()
}
else {
fatalError()
}
回复 :
["10 years from now , you'll look back and say I'm glad I started trading","I always define my risk and I don't have to worry about it","For trading success , there's a realization that when you don't care , you do well and when you try too hard , you don't .","Necessity never made a good bargain.","When a falling stock becomes a screaming buy because it cannot conceivably drop further , try to buy it thirty percent lower .","There are infinite number of ways to make money in markets & in life , Find ONE that works for you.","Get comfortable with being uncomfortable !.","The markets are always changing , and they are always the same.","You can't control how you feel . But you can always to choose how you act !","If what you're looking for is an excuse you'll find one !"]
解决方案
看起来响应是一个数组而不是一个字符串,所以将您的处理更改data
为
guard let data = data else {
//error handling...
return
}
do {
if let array = try JSONSerialization.jsonObject(with: data) as? [String] {
let quotes = DataModel(quotes: array)
self.delegate?.didGetData(data: quotes)
}
} catch {
print(error)
//error handling...
}
这假设DataModel
可以使用数组进行初始化,如果不是,您需要先执行以下操作以将数组的元素合并为字符串
let string = array.joined(separator: " ")
查看屏幕截图,我怀疑这并不容易,但处理数组内容的最佳方法超出了这个问题
推荐阅读
- sql - 基于是否存在条件检查的 SQL 查询
- python - Python 日志记录中的波斯语/阿拉伯语字符
- c# - 从 Graph API 获取全局地址列表
- google-maps - 谷歌地图地面叠加颤动
- python - 乳胶到 sympy 的转换
- powershell - PowerShell 创建 WMI 类
- windows - 通过 USB 列出连接设备的 CMD 命令?
- unit-testing - 如何用 jest 对这个 vue 组件进行单元测试
- node.js - 通过 multer 创建 ReadStream 并将文件上传到远程服务器
- python - Dataframe 无法正确设置 matplotlib 使用的索引