我有一个快速的应用程序Swift 3
,它与服务器交互以获取数据。现在我仍然可以成功连接到服务器。问题是当我想从JSON
结果中获取特定数据来设置标签文本值时,我总是在控制台中得到值Optional(x)
,标签值始终是{{1} }。
这是我从服务器收到的数据格式:
nil
这就是我得到它的方式:
[A: 1,
B: 2,
C: 3]
修改 我也可以获得这些格式:
案例1:
let task = session.dataTask(with: request) { data, response, error in
do {
guard let data = data else {
throw JSONError.NoData
}
guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary else {
throw JSONError.ConversionFailed
}
self.labelA.text = json[“A”] as? String
} catch let error as JSONError {
print(error.rawValue)
} catch let error as NSError {
print(error.debugDescription)
}
}
task.resume()
案例2:
[
{
id: 1,
fieldA: “nameA”,
fieldB: [“textA”, “textB", “textC”, “textD”],
fieldC: “nameC”
}
]
fieldB是一个String
数组答案 0 :(得分:1)
首先,除非你别无选择,否则永远不要在Swift中使用NSDictionary
。使用Swift原生类型。
其次,字典中的结果值似乎是Int
而不是String
。
...
guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Int] else {
throw JSONError.ConversionFailed
}
if let jsonA = json["A"] {
self.labelA.text = "\(jsonA)"
}
如果值为String
...
guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:String] else {
throw JSONError.ConversionFailed
}
if let jsonA = json["A"] {
self.labelA.text = jsonA
}
可以使用以下代码解析 案例1 , nil coalescing operator ??
在密钥不存在的情况下分配默认值。
guard let jsonArray = try JSONSerialization.jsonObject(with: data, options: []) as? [[String:Any]] else {
throw JSONError.ConversionFailed
}
for json in jsonArray {
let identifier = json["id"] as? Int ?? 0
let fieldA = json["fieldA"] as? String ?? ""
let fieldB = json["fieldB"] as? [String] ?? [String]()
let fieldC = json["fieldC"] as? String ?? ""
}
案例2 是字典[String:Any]
,与案例1相同但没有数组循环。
答案 1 :(得分:0)
始终在主线程上运行UI内容:
if let text = json[“A”] as String {
DispatchQueue.main.async {
self.labelA.text = text
}
}