用 Swift 解析 JSON
Posted
技术标签:
【中文标题】用 Swift 解析 JSON【英文标题】:parsing JSON with Swift 【发布时间】:2016-07-28 11:09:22 【问题描述】:我从 android 编程到 Swift ios 编程,很难解析 json 这是我尝试解析的字符串:
"response":["uid":111,"first_name":"someName","last_name":"someLastName","photo_100":"http:someUrl/face.jpg"]
我如何尝试解析这个:
if let dict = Utils.convertStringToDictionary(response)! as? [String: AnyObject]
// this part is yet doing ok
if let response = dict["response"] as? [String: AnyObject]
NSLog("let response \(response)")
if let first_name = response["first_name"] as? String
NSLog("first_name = \(first_name)")
else
NSLog("not an []")
日志消息给我“不是 []”,因为它无法生成响应对象。据我了解,我做得对,因为 [String: AnyObject]
是我的 json 的“响应”正文中的内容
以防万一,这是我的 Utils.convertStringToDictionary 方法:
public static func convertStringToDictionary(text: String) -> [String:AnyObject]?
if let data = text.dataUsingEncoding(NSUTF8StringEncoding)
do
let json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as? [String:AnyObject]
return json
catch
NSLog("Something went wrong")
return nil
【问题讨论】:
您的“响应”参数是数组而不是字典 【参考方案1】:Array in swift denotes with []
Dictionary in swift denotes with [:]
your response parameter is array of dictionary ... so it denotes with [[:]]
所以只需使用[[String: AnyObject]]
解析它
if let response = dict["response"] as? [[String: AnyObject]]
for user in response
NSLog("let response \(user)")
if let first_name = user["first_name"] as? String
NSLog("first_name = \(first_name)")
【讨论】:
能否请您解释一下 [[String: AnyObject]] 中的这个双方括号吗? 非常感谢!所以,响应实际上是一个字典数组,对吧? 是的......在这个answer..我确实解释了JSON中的括号,大括号暗示了什么......它可能对你有帮助【参考方案2】:这里的问题是响应是array
if let response = dict["response"] as? NSArray
for value in response as? NSDictionary
print(value["uid"]) /// prints 111
print(value["first_name"]) /// prints someName
【讨论】:
那你能告诉我如何解析它吗?我有点困惑,因为实际上它是一个 HashMap试试这个代码
if let dict = Utils.convertStringToDictionary(response)! as? [String: AnyObject]
// this part is yet doing ok
if let response = dict["response"] as? NSArray
NSLog("let response \(response)")
for dict in response
if let first_name = dict["first_name"] as? String
NSLog("first_name = \(first_name)")
else
NSLog("not an []")
【讨论】:
以上是关于用 Swift 解析 JSON的主要内容,如果未能解决你的问题,请参考以下文章