0

I am facing some difficulties with parsing JSON - I have followed a tutorial for receiving data from SQL database. When I try to return and Array over to Swift it's ok, BUT I can't call any members of the Array.

Swift:

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 (simplified):

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

Any advice would be helpful.

1 Answer 1

3

The problem is that your response is not Dictionary - it is an Array. But it can also a dictionary depending on server response. So you will have to put a check of either response is a dictionary or an Array. Your code should handle that, for example like this:

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)")
}    
Sign up to request clarification or add additional context in comments.

1 Comment

my pleasure. This is just to avoid that error. In case server send a signle object or an array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.