将JSON响应概括为函数参数

时间:2018-09-27 09:51:27

标签: ios swift json-serialization

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]]吗?

1 个答案:

答案 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;
 }

}