使用SwiftyJson解析Json

时间:2015-08-17 21:23:49

标签: ios json swift

我能够解析整个JSon数组。它输出到控制台没有问题。我似乎无法从数组中得到各个参数...我的json看起来像:

[{
        City = NYC;
        Device = "<null>";
        DisplayAs = "Steve Hutson";
        FirstName = Steve;
        LastName = Hutson;
        MobilePhone = "000-000-0000";
        Org = "<null>";
        Region = "";
        Role = INSPECTOR;
        SupervisorID = "73990";
        email = "email@email.com";
        fLast = shutson;
        "gz_modtimestamp" = "2015-07-28 14:42:41";
        id = 96;
        isActive = YES;
        lastupdated = "<null>";
        sendemail = 1;
        token = "<null>";
        userpassword = "xxx";
    },{
        City = DET;
        Device = "<null>";
        DisplayAs = "Filipe Washington";
        FirstName = Filipe;
        LastName = Washington;
        MobilePhone = "000-000-0000";
        Org = "<null>";
        Region = "";
        Role = INSPECTOR;
        SupervisorID = "6567";
        email = "email@email.com";
        fLast = shutson;
        "gz_modtimestamp" = "2015-07-28 13:02:09";
        id = 93;
        isActive = YES;
        lastupdated = "<null>";
        sendemail = 1;
        token = "<null>";
        userpassword = "xxx";
    }]

在我的主ViewController.swift文件中,我的json请求如下:

    var myData:NSData = getJSON("http://xxxx/getusersData.php")

    var myDict:NSArray = parseJSON(myData)

    println(myDict)

这打印我的整个json对象,这是完美的。不过我的问题是,如何才能获得数组中的FirstName?按索引这是有效的:

println(myDict[0]["FirstName"])但是,它只会带回一个项目。

我正在尝试将特定的json项插入到我正在使用SQLite.swift的sqlite中,但我需要知道如何检索特定的项参数,就像我使用AJAX一样。

我正在尝试检索FirstName,Email和UserPassword信息。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:2)

您可以迭代JSON对象并检索该信息:

for (index: String, subJson: JSON) in json {
    //Do something you want
    var firstName = subJson["FirstName"].stringValue
    var email = subJson["email"].stringValue
    var userPassword = subJson["userpassword"].stringValue
    // Build the sqlite query with the variables here 
} 

作为澄清,您不像json["FirstName"]那样直接访问值,您还必须使用SwiftyJSON中的类型函数。在您的情况下,它们都是字符串,因此使用stringValue。如果您需要int,那就是intValue

如果字段是可选字段,还可以选择json["FirstName"].string。看看readme

相关问题