将 JSON 响应概括为函数参数
Generalising JSON response as function parameter
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]]
?
在下面的代码中,您可以看到使用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;
}
}
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]]
?
在下面的代码中,您可以看到使用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;
}
}