【问题标题】:Generalising JSON response as function parameter将 JSON 响应概括为函数参数
【发布时间】:2018-09-27 09:51:27
【问题描述】:

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

【问题讨论】:

  • 只需使用Any? 并在函数内部尝试可选展开为? [任何] & [AnyHashable : 任何]
  • 不相关但String.Encoding(rawValue: String.Encoding.utf8.rawValue) 太可怕了。您可以将其替换为 .utf8。而mutableContainers 在 Swift 中毫无意义。
  • @RatulSharker:让我检查一下。希望能转换成字典和数组
  • @vadian :感谢您的提示。

标签: ios swift json-serialization


【解决方案1】:

在下面的代码中,你可以看到使用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;
 }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-23
    • 2021-06-06
    • 2018-11-01
    • 1970-01-01
    • 2015-01-13
    • 1970-01-01
    • 2019-08-06
    • 2022-01-23
    相关资源
    最近更新 更多