从json字符串中提取值

时间:2016-01-27 21:19:35

标签: json swift swift2 nsjsonserialization

下面是我获得的json数据中的json字符串并转换为字符串。我需要提取order_id,order_number,price等值。

Optional({
    msg = Success;
    name = "Add Order";
    "order_id" = 40509;
    "order_number" = 012720380116;
    "price" = 115;
    status = 1;
})

我试图用NSJSONSerialization.JSONObjectWithData获取值,但没有给我任何东西。我的代码有什么问题,有人可以看看吗?

do {
let json:AnyObject? = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
if let order_number = json!["order_number"] as? String {
print(order_number)
}

2 个答案:

答案 0 :(得分:1)

你需要适当地施放。

let json = try 
   NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
   as! [String: AnyObject]

答案 1 :(得分:0)

最后,我在do-catch上使用了以下代码块,并且它正常工作

                let jsonDict = try NSJSONSerialization.JSONObjectWithData(data2, options: NSJSONReadingOptions(rawValue: 0)) as? NSDictionary
            if let stat = jsonDict!["status"] {
                if stat as! NSObject == 1 {
                    let order_id = jsonDict!["order_id"]
                    let order_number = jsonDict!["order_number"]
                    let price = jsonDict!["price"]

                }
            }
相关问题