JSON序列化:
var responseDict: [AnyHashable : Any]? = nil
if let anEncoding = responseString?.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) {
responseDict = try! JSONSerialization.jsonObject(with: anEncoding, options: .mutableContainers) as? [String : Any]
}
我正在此函数中传递此responseDict:
func apiClientDidFinishWithResponse(response: [AnyHashable : Any]? {
}
现在,您刚刚意识到 responseDict 也可以是一个数组。我应该将 responseDict 保留为什么? Any
,[AnyHashable : Any]
,[[AnyHashable : Any]]
吗?
答案 0 :(得分:0)
在以下代码中,您可以看到使用json时可能遇到的所有应用程序。
var responseDict: Any? = nil
let responseString : String? = "[\"For\", \"BW\", \"Fit\"]"
if let anEncoding = responseString?.data(using: .utf8) {
responseDict = try! JSONSerialization.jsonObject(with: anEncoding, options: .mutableContainers) as? Any
}
apiClientDidFinishWithResponse(response: responseDict)
func apiClientDidFinishWithResponse(response: Any?) {
switch response {
case is [String: Any]:
print (response) ; //"{\"F\":1, \"B\":12, \"Fi\":11}"
case is [[String: Any]]:
print (response); // "[{\"Fd\":1}, {\"BM\":12}, {\"Fi\":11}]"
case is [Any]:
print (response) // "[\"For\", \"BW\", \"Fit\"]"
default : break;
}
}