1

I receive data from php file with this format:

 {"object:value", "object2:value2"...}
 {"object:value", "object2:value2"...}

I know how to parse this in Swift2 using next code repeatedly changing separatedBy string:

  if let url = NSURL(string: strURL), let data = NSData(contentsOfURL: url) {
        let strResult = NSString(data: data, encoding: NSUTF8StringEncoding)

    }
 tareas = strResult!.componentsSeparatedByString(",")

But I want parse this more easily. I have read others questions and answers but the format to parse was:

[
 {"person": {"name":"Dani","age":"24"}},
 {"person": {"name":"ray","age":"70"}}
]

And my data is different. How can I do this more easily?

Thanks!

2 Answers 2

1

You can read it as a Array like this

First of all you need to convert your data in valid json like this and then access it

var result: NSArray = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSArray
            println("result:  \(result)")

Ex.

        var str = "[{\"person\": {\"name\":\"Dani\",\"age\":\"24\"}},{\"person\": {\"name\":\"ray\",\"age\":\"70\"}}]"

        var data : NSData = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!

        var result: NSArray = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSArray
        println("Response:  \(result)")
        println("Oth Object:  \(result[0])")

Output

Response:  (
        {
        person =         {
            age = 24;
            name = Dani;
        };
    },
        {
        person =         {
            age = 70;
            name = ray;
        };
    }
)
Oth Object:  {
    person =     {
        age = 24;
        name = Dani;
    };
}
Sign up to request clarification or add additional context in comments.

6 Comments

I have used this code adapted to Swift2 latest version like: let jsonResults : NSArray do { jsonResults = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSArray print("result: (jsonResults)") // success ... } catch let error as NSError { // failure print("Fetch failed: (error.localizedDescription)") } And I get this error: "Fetch failed: The data couldn’t be read because it isn’t in the correct format."
@user3745888 Please see my updated answer. Which is working proper at my end. This may be happening due to invalid json. So make sure your json is valid or not.
Oh!, so I have a problem in my json format from php... I not get ar str = "[{\"person\": {\"name\":\"Dani\",\"age\":\"24\"}}, format. I get: ar str = " {"name":"Dani","age":"24"}, without person. Then I should write another question about write correctly result of my query in php to send a json correctly...
is it your response from server -> {"name":"Dani","age":"24"} ??
yes it is my response. Is the array result of a "inner join" mysql query
|
0

I suggest you to use SwiftyJSON (6k+ stars) library that converts response to JSON object. Something like:

   if let url = NSURL(string: strURL), let data = NSData(contentsOfURL: url) {
        let json = JSON(data: data!)
    }

After that you can easily extract any info from JSON:

for item:JSON in json.arrayValue{
    let person = item["person"].dictionaryValue
    //...
}

Playground printscreen

Comments

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.