使用swift解析json JSON数组

时间:2014-10-09 10:15:49

标签: ios json swift

我正在做一个与服务器通信的IOS(swift)应用程序。 来自服务器的响应是一个包含一些JSON对象的JSON数组。 当我通过控制台字符串显示响应时很好:

[{"NAME":"","SURNAME":"","ID":5,"USERNAME":"dpcabo2"},{"NAME":"","SURNAME":"","ID":10,"USERNAME":"default"},{"NAME":"","SURNAME":"","ID":11,"USERNAME":"esteban"}]

但是当我尝试使用此解析器将此信息解析为json:

   var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(self.my_data!,
               options:NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

println("\(jsonResult)")

app崩溃。

所以我需要一个解决方案来正确解析这些信息。

Ps.self.my_data!是一个NSMutableData。

由于

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码进行解析。它可以正确打印和解析对象。

import Foundation

let jsonObject: [AnyObject] = [
    ["NAME":"","SURNAME":"","ID":5,"USERNAME":"dpcabo2"],
    ["NAME":"","SURNAME":"","ID":10,"USERNAME":"default"],
    ["NAME":"","SURNAME":"","ID":11,"USERNAME":"esteban"]
]


let jsonOptional: AnyObject! = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions(0), error: nil)

回复如下:

[["USERNAME": "dpcabo2", "ID": 5, "NAME": "", "SURNAME": ""], 
["USERNAME": "default", "ID": 10, "NAME": "", "SURNAME": ""], 
["USERNAME": "esteban", "ID": 11, "NAME": "", "SURNAME": ""]]