【问题标题】:Issuing in getting JSON values SWIFT Alamofire发布获取 JSON 值 SWIFT Alamofire
【发布时间】:2018-05-13 20:15:10
【问题描述】:

我正在从服务器获取响应并将其转换为 NSDictionary。

Alamofire.request(URL, method: .post, parameters: parameters).responseJSON
        {
            response in

            if let result = response.result.value {
                let jsonData = result as! NSDictionary
                let recordJSON=jsonData.value(forKey: "records") as! NSDictionary
                let result = recordJSON.value(forKey: "result") as! NSArray
                print(result)

            }
    }

现在结果中的值是

(
    {
    imagePath = "/SERVER/api/upload/geRsB.jpeg";
    propertyId = 11;
    userId = 5;
},
    {
    imagePath = "/SERVER/api/upload/RebJC.jpeg";
    propertyId = 14;
    userId = 5;
},
    {
    imagePath = "/SERVER/api/upload/fuM3F.jpeg";
    propertyId = 18;
    userId = 5;
}
)

那么,现在我如何从结果的每个索引中获取更多值(imagePath,propertyId,userId)。

提前致谢。

【问题讨论】:

  • 不要在 Swift 中使用 NSDictionary 和/或 NSArray 进行 JSON 解析。阅读Decodable 上的文档以解析您的 JSON。

标签: swift alamofire swift4


【解决方案1】:

我推荐使用Decodable,但在你的情况下,你可以试试

 if let result = response.result.value as? [String:Any] {

    if let recordJSON = result["records"] as? String:Any] {

       if let result = recordJSON["result"] as?  [Any] {

            print(result)

             for item in result  {

                   if let inner = item as? [String:Any] {

                       print(inner["imagePath"])

                       print(inner["propertyId"])

                       print(inner["userId"])

                   }

             }
        }
    }
}

【讨论】:

    【解决方案2】:

    您必须使用 Codable 或 decodeable 来解析响应:

    1:这是响应数据的结构

    struct ImageData: Codable {
        let imagePath: String
        let propertyId: Int
        let userId: Int
    }
    

    2:然后使用这个结构体来解析数据:

    Alamofire.request(URL, method: .post, parameters: parameters).responseJSON
            { response in
    
        if let result = response.result.value {
           let jsonData = try JSONSerialization.data(withJSONObject: result, options: JSONSerialization.WritingOptions.prettyPrinted)
           let myStruct = try JSONDecoder().decode([ImageData].self, from: jsonData)
                    print(result)
    
             }
        }
    

    3:然后你可以像这样使用这个解析第一个对象结果:

    let imagePath = myStruct[0].imagePath
    let propertyId = myStruct[0].propertyId
    let userId = myStruct[0].userId
    

    或者你可以像这样不使用 Parse 直接使用:

       for data in result  {
    
          if let innerData = data as? [String:Any] {
            let imagePath = innerData["imagePath"]
            let propertyId = innerData["propertyId"]
            let userId = innerData["userId"]
         }
      }
    

    【讨论】:

    • 为此,返回的 json 必须看起来像 OP 的问题,但实际上它不是 OP 解析它,直到他捕获数组,所以你应该这样做 result NSArray 不是 response.result.value 这是一个字典
    【解决方案3】:

    如果你的回复是这样的

    [
      {
        "imagePath": "/SERVER/api/upload/geRsB.jpeg",
        "propertyId": 11,
        "userId": 5
      },
      {
        "imagePath": "/SERVER/api/upload/geRsB.jpeg",
        "propertyId": 11,
        "userId": 5
      }
    ]
    

    你可以像这样使用可编码协议

    import Foundation
    
    typealias Users = [UserElement]
    
    struct UserElement: Codable {
        let imagePath: String
        let propertyID, userID: Int
    
        enum CodingKeys: String, CodingKey {
            case imagePath
            case propertyID = "propertyId"
            case userID = "userId"
        }
    }
    
    // MARK: Convenience initializers
    
    extension UserElement {
        init(data: Data) throws {
            self = try JSONDecoder().decode(UserElement.self, from: data)
        }
    }
    
    extension Array where Element == Users.Element {
        init(user data: Data) throws {
            self = try JSONDecoder().decode(Users.self, from: data)
        }
    }
    

    然后在Request中这样使用

     Alamofire.request(URL, method: .post, parameters: parameters).response
                {
                    response in
                   guard let data = response.data else {return}
                    let users = try? Array.init(user:data)
            }
    

    【讨论】:

      猜你喜欢
      • 2023-04-05
      • 2015-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多