简体   繁体   English

如何在swift4中解析对象内的JSON数组

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

I'M using tableview to parsing JSON data.我正在使用 tableview 来解析 JSON 数据。 the parse data in tableview in successful parsed on my tableView but the problem is users click the tableview cell to pass to details ViewController.But the problem is i can't parse JSON in details ViewController in tableview 中的解析数据在我的 tableView 上成功解析,但问题是用户单击 tableview 单元格传递给详细信息 ViewController。但问题是我无法在详细信息 ViewController 中解析 JSON

here is my JSON looks这是我的 JSON 外观

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

here is my code这是我的代码

  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()                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            

Please try this codes请试试这个代码

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) }

Parse json in swift4 using Codable protocol.使用 Codable 协议在 swift4 中解析 json。 declare your model like this:像这样声明你的模型:

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

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

then, after getting data, use this:然后,在获取数据后,使用这个:

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

Note that your json is array not dictionary!请注意,您的 json 是数组而不是字典!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM