使用Swift解析JSON

时间:2015-04-16 10:16:34

标签: json swift

我在解析JSON时面临一些困难 - 我已经按照从SQL数据库接收数据的教程。当我尝试返回并Array转到Swift时,它可以,但我无法呼叫Array的任何成员。

夫特:

let myUrl = NSURL(string: "XXXXXXXXXXXXXXXX.Fr");
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";

// Compose a query string
let postString = "Pseudo=\(PseudoVar)";

request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
    data, response, error in

    if error != nil {
        println("error=\(error)")
        return
    }

    // You can print out response object
    println("response = \(response)")

    // Print out response body
    let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
    println("responseString = \(responseString)")

    //Let's convert response sent from a server side script to a NSDictionary object:

    var err: NSError?
    var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error:&err) as? NSDictionary

    if let parseJSON = json {
        // Now we can access value of First Name by its key
        var firstNameValue = parseJSON["firstName"] as? String
        println("firstNameValue: \(firstNameValue)")
    }    
}   
task.resume()

PHP(简化):

<?php
    array("Pseudo0" => "Hello", "Pseudo1" => "Good Morning");
    echo json_encode($returnValue);             
?>

任何建议都会有所帮助。

1 个答案:

答案 0 :(得分:2)

问题是您的回复不是Dictionary - 它是Array。但它也可以是字典,具体取决于服务器响应。因此,您必须检查响应是字典还是数组。您的代码应该处理它,例如:

if let jsonArray = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error:&err) as? [NSDictionary] {
    for jsonDict in jsonArray {
        var firstNameValue = jsonDict["firstName"] as? String
        println("firstNameValue: \(firstNameValue)")
    }
} else if let jsonDict = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error:&err) as? NSDictionary {
     var firstNameValue = jstonDict["firstName"] as? String
     println("firstNameValue: \(firstNameValue)")
}