JSON对结构和数组Swift的响应

时间:2018-07-07 15:45:41

标签: arrays json swift httpresponse decoding

当前,我有一个名为User的结构,它定义了我想从HTTP响应中解码的变量。然后,我有一个名为users的数组,其中将包含响应。如您所见,我在random8函数中填充用户,但是现在在random1函数中,我遇到了问题。在random1函数中,我只有1个用户而不是8个用户,并且我尝试获取该数据并将当前用户之一替换为新数据。我可以在我的代码中成功地做到这一点(通过提取每个值),但是我敢肯定我没有以标准方式来做到这一点。请让我知道是否有更好的方法。

请记住,在viewDidLoad上调用random8,然后在他们点击特定按钮时出现random1,因此我要替换一个特定用户索引的数据。

 struct User: Decodable {
    var id: Int
    var first_name: String
    var last_name: String
    var picture_url: String
    var points: Int
    var school: String
    var grade: Int
}

 var users = [User]()

func getRandom8() {
    let url = URL(string: "https://somewebsite.com/users/random/eight")
    let session = URLSession.shared

    let request = NSMutableURLRequest(url: url!)
    let preferences = UserDefaults.standard
    request.addValue("JWT \(preferences.object(forKey: "token") as! String)", forHTTPHeaderField: "Authorization")
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.httpMethod = "GET"

    let task = session.dataTask(with: request as URLRequest, completionHandler: {
        (data, response, error) in
        do {
            self.users = try JSONDecoder().decode([User].self, from: data!)

            DispatchQueue.main.async (
                execute: self.loadRandom8
            )

        } catch {
            print("error in getting data")
        }
    })

    task.resume()

}

func getRandom1(index:Int) {
    let url = URL(string: "https://somewebsite.com/users/random/one")
    let session = URLSession.shared

    let request = NSMutableURLRequest(url: url!)
    let preferences = UserDefaults.standard
    request.addValue("JWT \(preferences.object(forKey: "token") as! String)", forHTTPHeaderField: "Authorization")
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.httpMethod = "GET"
    //write a statement that says if that user is already there, do the call again
    let task = session.dataTask(with: request as URLRequest, completionHandler: {
        (data, response, error) in

        do {
            let responseObject = (try? JSONSerialization.jsonObject(with: data!)) as? [String: Any]
            print(responseObject)

            let indexFirstName = responseObject?.index(forKey: "first_name")
            let indexId = responseObject?.index(forKey: "id")
            let indexPictureURL = responseObject?.index(forKey: "picture_url")
            let indexPoints = responseObject?.index(forKey: "points")
            let indexSchool = responseObject?.index(forKey: "school")
            let indexGrade = responseObject?.index(forKey: "grade")
            let indexLastName = responseObject?.index(forKey: "last_name")

            self.users[index].last_name = responseObject![indexLastName!].value as! String
            self.users[index].first_name = responseObject![indexFirstName!].value as! String
            self.users[index].id = responseObject![indexId!].value as! Int
            self.users[index].picture_url = responseObject![indexPictureURL!].value as! String
            self.users[index].points = responseObject![indexPoints!].value as! Int
            self.users[index].school = responseObject![indexSchool!].value as! String
            self.users[index].grade = responseObject![indexGrade!].value as! Int


            DispatchQueue.main.async (
                execute: self.loadRandom8
            )

        } catch {
            print("error in getting data")
        }
    })

    task.resume()

}

1 个答案:

答案 0 :(得分:1)

random/one请求中没有看到JSON格式,这很难说,但是您应该能够使用

解析单个User实例。
let user = try JSONDecoder().decode(User.self, from: data!)

而不是求助于JSONSerialization

并将数据放入users数组中,执行users[index] = user