你好,我从后端获取了以下 API 响应。
在这里,我需要从以下 [Any] 类型中检索出 "userId"。
[{
"userId" : "5e633967c04aff49e5e22c5b",
"onlineStatus" : 1
}]
我尝试使用以下代码,但在我的情况下它出现错误。
let data = Array(chatdataArray) as? [[String:Any]]
print(data)
你好,我从后端获取了以下 API 响应。
在这里,我需要从以下 [Any] 类型中检索出 "userId"。
[{
"userId" : "5e633967c04aff49e5e22c5b",
"onlineStatus" : 1
}]
let data = Array(chatdataArray) as? [[String:Any]]
print(data)
首先,将 Array[Any]
转换为字典数组 [[String: Any]]
,可以使用 guard let
或 if 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)
}
}
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)
}
首先,我将其初始化为字典数组,然后提取所需的项。
if let data = chatdataArray as? [[String: Any]]{
for item in data{
if let userId = item["userId"] as? String{
print(userId)
}
}
}
如果我正确理解了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]
。
你可以使用这个。
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)