【问题标题】:how to parse JSON array inside object in swift4如何在swift4中解析对象内的JSON数组
【发布时间】:2018-10-22 11:23:14
【问题描述】:

我正在使用 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()                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            

【问题讨论】:

  • [string: anyobject](小写)无法编译。 JSON 以括号 ([) 开头,因此它显然是一个数组。请阅读Correctly Parsing JSON 了解其中的区别。
  • 你的“didSelectCellAtIndexPath”方法在哪里?您只是向我们展示了解析,但您在进入详细视图时告诉我们它错误。如果这是问题,请向我们展示该代码。如果是解析,您是否将相同的信息解析两次?您不能将对象传递给您的详细视图吗?
  • 在 tableview 中我只解析一个对象,它是细节视图控制器中的 ID 有更多数据要解析所以我在细节视图控制器中再次解析

标签: ios json swift


【解决方案1】:

请试试这个代码

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

【讨论】:

    【解决方案2】:

    使用 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 是数组而不是字典!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多