【问题标题】:How to print array of dictionary value in swift [closed]如何在swift中打印字典值数组[关闭]
【发布时间】:2020-06-19 20:20:55
【问题描述】:

您好,我从后端收到 api 响应,如下所示。

这里我需要从以下 [Any] 类型中检索“userId”。

[{
  "userId" : "5e633967c04aff49e5e22c5b",
  "onlineStatus" : 1
}]

我尝试使用以下代码,但在我的情况下它给出了错误。

let data = Array(chatdataArray) as? [[String:Any]]
print(data)

【问题讨论】:

  • 尝试使用json解码,例如google “Swift Codable”

标签: ios arrays swift dictionary


【解决方案1】:

首先将数组[Any] 转换为字典数组[[String: Any]],使用guard letif let

guard let arrChatData = chatdataArray as? [[String: Any]] else { return }

print("User Id :: ", arrChatData[0]["userId"])

或者

Model 用于 API 响应,将 ObjectMapper 用于地图数据。

用法:

创建模型。

import Foundation
import ObjectMapper

//MARK: - ChatDetails
struct ChatDetails: Mappable {

    var chatDataArray: [ChatDataArray]?

    init?(map: Map) {}

    mutating func mapping(map: Map) {

        self.chatdataArray <- map["chatdataArray"]
    }
}

//MARK: - ChatDataArray
struct ChatDataArray: Mappable {

    var onlineStatus: Int?
    var userId: String?

    init?(map: Map) {}

    mutating func mapping(map: Map) {

        self.onlineStatus <- map["onlineStatus"]
        self.userId <- map["userId"]
    }
}

Models 地图 API 响应设置后。

if let responseDict = response as? [String: Any], responseDict.keys.count > 0 {
    if let chatDetails = Mapper<ChatDetails>().map(JSON: responseDict) {

        var arrChatList = chatDetails.chatdataArray
        print("User ID :: ", arrChatList[0].userId)
    }
}

【讨论】:

    【解决方案2】:
    class Model:NSObject,Codable{
        var userId: String?
        var onlineStatus: Int?
    }
    
    do{
    
        let object = [["userId":"123"],["userId":"456"]]
    
        let jsonData = try JSONSerialization.data(withJSONObject: object, options: [])
        let array = try JSONDecoder().decode(Array<Model>.self, from: jsonData)
    
        let model = array[0]
        let userId = model.userId
    
        print(array)
        print(model)
        print(userId)
    
    }catch{
        print(error)
    }
    

    【讨论】:

      【解决方案3】:

      你可以用这个。

      import Foundation
      
      extension Data {
          var prettyPrintedJSONString: NSString? { /// NSString gives us a nice sanitized debugDescription
              guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
                    let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
                    let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
      
              return prettyPrintedString
          }
      }
      
      
      let str = "[{\"userId\" : \"5e633967c04aff49e5e22c5b\", \"onlineStatus\" : 1 }]".data(using: .utf8)!.prettyPrintedJSONString!
      debugPrint(str)
      

      【讨论】:

      • 当你有一个原生的 swift String 类时,没有理由使用 NSString
      【解决方案4】:

      如果我正确理解了 OP 标准,这看起来是使用 Swift 高阶函数方法的好案例。

      let dic: [Any] = [["userId": "5e633967c04aff49e5e22c5b",
                          "onlineStatus": 1],
                        ["userId": "aaaa",
                          "onlineStatus": 0]]
      let userIdValues = dic.compactMap{ ($0 as? [String: Any])?["userId"] }
      print(userIdValues) 
      

      屈服

      ["5e633967c04aff49e5e22c5b", "aaaa"]
      

      如果Any 元素在as? 期间不会转换为[String: Any]compactMap 将过滤掉 nil 条目

      【讨论】:

        【解决方案5】:

        首先我将其初始化为字典数组,然后获取所需的项目。

        if let data = chatdataArray as? [[String: Any]]{
              for item in data{
               if let userId = item["userId"] as? String{
                   print(userId)
              }
             }
        }
        

        【讨论】:

        • 请解释你的答案。
        • @LajosArpad 谢谢!解释。并且效果很好,不知道谁拒绝了我的回答以及他/她为什么这样做。
        • 我认为投反对票的原因是,即使您的答案似乎是正确的,但它缺乏必要的教学元素来解释。我倾向于只对带有问题或答案的非常严重的问题投反对票,所以我没有对你的答案投反对票,但现在它值得投赞成票。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-26
        • 1970-01-01
        • 2019-04-10
        • 1970-01-01
        • 1970-01-01
        • 2019-02-01
        • 1970-01-01
        相关资源
        最近更新 更多