在Swift 4中将Json字符串转换为Json对象

我尝试将Json字符串转换为json对象,但在JSONSErialization之后,json中的输出为nil。

Response String: Optional("[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]") **I try to convert this string with my code below** let jsonString = response.result.value let data: Data? = jsonString?.data(using: .utf8) let json = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String:AnyObject] print(json ?? "Empty Data") 

我在下面的代码中使用了你的json字符串:

 let string = "[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]" let data = string.data(using: .utf8)! do { if let jsonArray = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [Dictionary] { } else { print("bad json") } } catch let error as NSError { print(error) } 

我得到了输出:

 [["form_desc": , "form_name": Activity 4 with Images, "canonical_name": df_SAWERQ, "form_id": 3465]] 

使用JSONSerialization总是觉得unwwty和笨拙,但是随着Codable在Swift 4中的到来Codable 。如果你在一个简单的struct前面使用[String:Any]它会……伤害。 在游乐场看看这个:

 import Cocoa let data = "[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]".data(using: .utf8)! struct Form: Codable { let id: Int let name: String let description: String? private enum CodingKeys: String, CodingKey { case id = "form_id" case name = "form_name" case description = "form_desc" } } do { let f = try JSONDecoder().decode([Form].self, from: data) print(f) print(f[0]) } catch { print(error) } 

只需极少的努力处理,这将感觉更舒适。 如果您的JSON无法正确解析您将获得更多信息。