首页 > 解决方案 > 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 !"]

截屏

标签: arraysjsonswiftpoststruct

解决方案


看起来响应是一个数组而不是一个字符串,所以将您的处理更改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: " ")

查看屏幕截图,我怀疑这并不容易,但处理数组内容的最佳方法超出了这个问题


推荐阅读