2

I am trying to do a simple JSON string to Object conversion. Here is the code:

let u = "somehost.com/api/1/ipa/2"
let url = NSURL(string: u )!

let data = NSData(contentsOfURL: url)!

let parsed: AnyObject? = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) 

if let json = parsed as? [String: AnyObject]{
    // never enters this if statement.
}

But it will not unwrap correctly. Seems to me that this should be much simpler. Could someone please help? Also using "Xcode 7.3 and swift 2.2".

I want to avoid using a third party library.

6
  • Can you show the response of this api? Commented Aug 27, 2016 at 4:37
  • can you show your proper URL or Valid URL Commented Aug 27, 2016 at 4:45
  • If it does not pass the optional binding it's most likely not [String:AnyObject]. Show the beginning of the JSON. Commented Aug 27, 2016 at 4:49
  • It might be a list of dicts like: as? [[String: AnyObject]] { ... Commented Aug 27, 2016 at 4:54
  • api link is not in production, but the json string that is returned is {"a":"b","c":"d"}. Also it is not in a list. @NDoc Commented Aug 27, 2016 at 5:07

3 Answers 3

1

Sample Json Parsing Fetch and read like this easy and simple understanding process. Hit the below link you will see the response as dictionary and inside dictionary there is an array.......

   let WebURL = "http://api.randomuser.me/"

    let url2 = NSURL(string:WebURL)

    let data = NSData(contentsOfURL: url2!)

    do
    {

       let dictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! NSMutableDictionary

        print(dictionary)

        let arrayOfValues = dictionary .objectForKey("results") as! NSMutableArray

        print(arrayOfValues)


        for var i = 0; i<arrayOfValues.count; i++ {


            let resultDictInsideArray = arrayOfValues.objectAtIndex(i)

            let NameDict = resultDictInsideArray.objectForKey("name")!

            let locDict = resultDictInsideArray.objectForKey("location")!



            print(NameDict.objectForKey("title")!)
            print(locDict.objectForKey("street")!)



        }


    }catch {

    print("error")


    }

If your URL has spaces write code for URL like this

 let url = NSURL(string: stringUrl.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!)!
Sign up to request clarification or add additional context in comments.

1 Comment

Does not work... I am getting this error Could not cast value of type '__NSCFString' to 'NSMutableDictionary'
0

Are you sure what is returned is not an array rather than an object?

Have you tried this:

if let json = parsed as? [AnyObject]{
}

Comments

0
       func getDataFromServer(myGetUrl : URL) {
        let url = myGetUrl
        //create the session object
        let session = URLSession.shared

        //now create the URLRequest object using the url object
        let request = URLRequest(url: url )

        //create dataTask using the session object to send data to the server
        let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in

            guard error == nil else {
                print(error as Any)
                return
            }

            guard let data = data else {
                return
            }

            do {
                //create json object from data
                if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [[String:AnyObject]] {
                    //print(json)
                    self.getResponsedata = json
                    //print("Here: \(self.getResponsedata)")
                    self.getDelegate.GetdataReceivedFromServer(data: self.getResponsedata , url : myGetUrl)
                }
            } catch let error {
                print(error.localizedDescription)
            }
        })
        task.resume()
    }
}

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.