簡體   English   中英

如何在swift4中解析對象內的JSON數組

[英]how to parse JSON array inside object in swift4

我正在使用 tableview 來解析 JSON 數據。 tableview 中的解析數據在我的 tableView 上成功解析,但問題是用戶單擊 tableview 單元格傳遞給詳細信息 ViewController。但問題是我無法在詳細信息 ViewController 中解析 JSON

這是我的 JSON 外觀

[
{
    "id": "263",
    "userId": "2692"
 }
 ]

這是我的代碼

  guard let url = URL(string: URL API) else { return }
    var request = URLRequest(url: url)
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("Bearer \(AccessToken!)", forHTTPHeaderField: "Authorization")
    request.httpMethod = "GET"

    let session = URLSession.shared
    session.dataTask(with: request) { (data, response, error) in 
    do {
            let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [string: anyobject]

                print(json)
         label.text = json["id"] as? string

        }catch {


        }

 }.resume()                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            

請試試這個代碼

do {
   if let json = try JSONSerialization.jsonObject(with: data!) as? [[String: String]] {
      for data in json {

          label.text  = data["id"] as? String
      }
   }
} catch { print(error) }

使用 Codable 協議在 swift4 中解析 json。 像這樣聲明你的模型:

struct Model: Codable {
    let id: Double
    let userId: Double

    enum CodingKeys : String, CodingKey {
        case id = "id"
        case userId = "userId"
    }
}

然后,在獲取數據后,使用這個:

do {
    let arrayValue = try JSONDecoder().decode([Model], from: data)
} 
catch {
}

請注意,您的 json 是數組而不是字典!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM