如何从json获取值并将其存储为变量

时间:2016-05-15 13:22:28

标签: ios json swift

我在一个项目下。在我获取一些数据并且我需要取“_id”的值。并且我需要分配给一个变量以供将来使用。下面的json响应是我因为我需要单独使用"_id" = 57383a6f74737692116174b9;。我需要将此"_id"分配给某个变量。但我不知道如何包装它并分配给变量。

{
    "__v" = 0;
    "_id" = 57383a6f74737692116174b9;
    "business_id" =     {
        "__v" = 0;
        "_id" = 56cbf2547bb6427e2ac93cde;
        "business_email" = "info@.com";
        "business_name" = "State ";
        "business_type" = 56cbed2e1c856c672a302ce4;
        "created_at" = "2016-02-23T05:47:00.966Z";
        email = "do@gmail.com";
        gender = male;
        images =         (
                        {
                url = "http://tor.jpg";
            },
                        {
                url = "http://tor.jpg";
            }
        );
        "is_deleted" = 0;
        languages =         (
            English,
            Punjabi,
            Hindi
        );
        latlng =         (
            "3.6465059",
            "-9.38014509999999"
        );
        location = "200 Bay St, Torky";
        "method_payment" =         (
            Cash,
            Visa,
            Mastercard
        );
        name = "Ms";
        "opening_hours" =         (
                        {
                Monday = "12:00pm - 09:00pm";
            },
                        {
                Tuesday = "12:00pm - 09:00pm";
            },
                        {
                Wednesday = "12:00pm - 09:00pm";
            },
                        {
                Thursday = "12:00pm - 09:00pm";
            }
        );
        password = 12345;
        "phone_no" = "+1 416";
        profileImageURL = "http://www.gospelherald.com/data/images/full.jpg";
        "social_links" =         {
            "fb_url" = "https://facebook.com/sbi";
            "google_url" = "https://google.com/sbi";
            "twitter_url" = "https://twitter.com/sbi";
        };
        specialities =         (
            Cafe,
            "Tea Room",
            "Bubble Tea"
        );
        status = 1;
        "updated_at" = "2016-02-23T05:47:00.966Z";
        username = douglous;
        videos =         (
                        {
                url = "https://www.youtube.com/watch?v=V87kFKgLOI0";
            },
                        {
                url = "https://www.youtube.com/watch?v=V87kFKgLOI0";
            }
        );
        "website_url" = "url";
    };
    "created_at" = "2016-05-15T08:59:27.797Z";
    "customer_id" = 56fa77437e9cb5140ac510e2;
    "is_deleted" = 0;
    status = 1;
    "updated_at" = "2016-05-15T08:59:27.797Z";
}

我的视图控制器中的代码:

 var BusinessData = DeleteFav?()

在我的 DeleteFav?()中我有一个变量。我需要将“_id”分配给该变量

 func Getthedtafromfavouritegetmethod () {

         let userToken = NSUserDefaults.standardUserDefaults().valueForKey("access_token") as! String;

        let headers = [
             "x-access-token": userToken,
            "cache-control": "no-cache",
            "postman-token": "8eaa2c68-a459-21bf-569e-1e049d804be2"
        ]

        var request = NSMutableURLRequest(URL: NSURL(string: "some url")!,
      cachePolicy: .UseProtocolCachePolicy,  timeoutInterval: 10.0)
        request.HTTPMethod = "GET"
        request.allHTTPHeaderFields = headers

        let session = NSURLSession.sharedSession()
        let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
            if (error != nil)
            {
                print(error)

                let ErrorAlert = UIAlertController(title: "Error", message: "Problem with internet connectivity or server, please try after some time", preferredStyle: UIAlertControllerStyle.Alert)

                // add an action (button)
                ErrorAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))

                // show the alert
                self.presentViewController(ErrorAlert, animated: true, completion: nil)
            }
            else
            {
                if let json = (try? NSJSONSerialization.JSONObjectWithData(data!, options: [])) as? Dictionary<String,AnyObject>
                {
                    let success = json["success"] as? Int

                    if(success == 1)
                    {

                        if let typeValues = json["data"] as? [NSDictionary]
                        {
                            dispatch_async(dispatch_get_main_queue(),{

                                for item in typeValues
                                {

                                    print(item)


                                }


                            })
                        }
                    }
                    else
                    {
                        let message = json["message"] as? String

                        let ServerAlert = UIAlertController(title: "Error", message: message, preferredStyle: UIAlertControllerStyle.Alert)

                        // add an action (button)
                        ServerAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))

                        // show the alert
                        self.presentViewController(ServerAlert, animated: true, completion: nil)
                    }
                }
            }
        })

        dataTask.resume()


    }

我在上面的完整代码中检查我是否从下面的代码中得到了正确答案:

for item in typeValues
 {
 print(item)
 }

那么如何在我的自定义类中为我的变量指定“_id”。我是ios的新手,并开始学习一些youtube视频。任何帮助对我都有用谢谢...... !!

已更新:

我有一个自定义类:

import UIKit

class DeleteFav: NSObject {

    var FavId : String?


    init(json:NSDictionary)
    {
        self.FavId = json["_id"] as? String

    }

}

1 个答案:

答案 0 :(得分:0)

您可以在https://github.com/ibireme/YYModel

上试用该库
// Convert json to model:
User *user = [User yy_modelWithJSON:json];

// Convert model to json:
NSDictionary *json = [user yy_modelToJSONObject];`