如何使用swift提取json对象?

时间:2015-09-12 06:34:28

标签: ios json swift

JSON功能:

func extract_json(data:NSString){

    var parseError: NSError?

    let jsonData:NSData = data.dataUsingEncoding(NSASCIIStringEncoding)!


  let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: &parseError)

    if (parseError == nil){

        if let coupon_list = json as? [String: AnyObject]{

            if let coupons = coupon_list["data"] as? [AnyObject]{

                for (var i = 0; i < coupons.count ; i++ ){

                    if let coupon_obj = coupons[i] as? NSDictionary{

                        let location: AnyObject? = coupon_obj.objectForKey("location")

                     //the print the value location
                     println(location)

//我只想在位置值之前获取数字键 这是我的Json对象,你可以看到

{
brand = "Mang Inasal";
category =     (
    2
);
desc = "Mang Inasal Salmonella Giveaway";
discount = 50;
"end_date" = 1443369600;
id = 2;
imgs =     (
    "http://mymegamobile.com/savvy/halo2x.png",
    "http://mymegamobile.com/savvy/bar_filter.png",
    "http://mymegamobile.com/savvy/bar_mega.png",
    "http://mymegamobile.com/savvy/box1.png",
    "http://mymegamobile.com/savvy/box2.png"
);
location =     {
    1435307555 = Baguio;
};
name = "Mang Inasal Halo Halo";
stamp = "2015-09-02 14:04:38";
"start_date" = 1438012800;
}

对象结构的结果如上。 如何在我的位置获取1435307555的值?

3 个答案:

答案 0 :(得分:0)

你可以这样做:

let yourObject = location?.objectForKey("165952298") as! String

答案 1 :(得分:0)

for (key,value) in coupon_list {
    println(key)
}

这样你就可以从JSON获得所有密钥

答案 2 :(得分:0)

func extract_json(data:NSString){

 var parseError: NSError?

 let jsonData:NSData = data.dataUsingEncoding(NSASCIIStringEncoding)!


 let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: &parseError) as! NSDictionary

   if (parseError == nil) { 

              for (var i = 0; i < json.count ; i++ ) { 

                    let location: AnyObject? = ((json)["location"] as! NSDictionary)["1435307555"]

                 //the print the value location
                 println(location)

              }


   }