如何在Swift中打印字典值的数组

3

你好,我从后端获取了以下 API 响应。

在这里,我需要从以下 [Any] 类型中检索出 "userId"。

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

我尝试使用以下代码,但在我的情况下它出现错误。
let data = Array(chatdataArray) as? [[String:Any]]
print(data)

1
尝试使用JSON解码,例如可以搜索“Swift Codable”。 - Joakim Danielson
5个回答

4

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

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

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

或者

使用Model来使用ObjectMapper将数据映射为API响应。

用法:

创建模型。

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

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

0

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

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

请解释你的答案。 - Lajos Arpad
@LajosArpad 谢谢!已经解释清楚了。它运行良好,不知道是谁对我的答案进行了负评,并且他/她出于什么原因这样做。 - Abdul Karim Khan
1
我认为被踩的原因是,尽管你的回答似乎是正确的,但它缺乏必要的解释性教学元素。我倾向于只在问题或答案涉及非常严重的问题时才会踩,所以我没有踩你的回答,但现在它值得被点赞了。 - Lajos Arpad

0

如果我正确理解了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"]

compactMap 会在 as? 转换时,过滤掉无效的 nil 条目,如果 Any 元素不能转换为 [String: Any]


0

你可以使用这个。

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。 - Joakim Danielson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接