简体   繁体   中英

Why do I get an error when trying to serializing JSON in Swift?

I just starting to learn swift. So I am a noob if it comes to swift. To try and practice it I am trying to make a grocery application for ios. But now I am stuck on probably one of the most basic things, serializing a JSON object without using a library so just with the standard swift code. So my question is can you help me solving my problem with serializing the data that I got from the api.

I am using postman to check what kind of response I get from the api. When I do a get to the api this is the response I get:

[
  {
    "id": 1,
    "name": "Regular List"
  },
  {
    "id": 2,
    "name": "List for diner"
  },
  {
    "id": 3,
    "name": "List 3"
  },
  {
    "id": 4,
    "name": "List for next week"
  },
  {
    "id": 6,
    "name": "Test name"
  }
]

In my swift code I am trying to get this response by doing this:

func getBoodschapListJSON(){
        let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
        let userId = prefs.integerForKey("UserId")
        let requestUrl = NSURL(string: "http://localhost:8080/api/lists/user/id/\(userId)")!
        let session = NSURLSession.sharedSession()

        let request = NSMutableURLRequest(URL: requestUrl)
        request.HTTPMethod = "GET"
        request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")

        session.dataTaskWithRequest(request, completionHandler: { (data, response, error) in

                do {
                    let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)

                    //Here comes some code to try and process the JSON object in the table View.
                } catch {
                    print("error serializing JSON: \(error)")
                }

        }).resume()
    }

But I never got a valid response I end up with the error: "error serializing JSON: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}"

I expect that it has something to do with the JSON not being in the right format so that NSJSONSerialization is able to interpret it. But I am not sure, I have looked at a several stack-overflow posts that had the same question as I have. Most of them said to use .AllowFragments but that did not resolve my error.

Would anyone be so kind to help me so I able to fix this error in my code?

Your URL looks a bit weird, but it is still possible for it to work like that. Try visit the URL in your browser (set an id for userId) and make sure it looks all right. If it does, make sure there is no html in your API's code. For example no meta tags (which you might be using).

If that doesn't work, maybe it's the code. Try mine:

let urlAsString = "http://localhost:8080/api/lists/user/id/\(userId)"
do {
    let jsonDict: NSDictionary = try NSJSONSerialization.JSONObjectWithData(NSData(contentsOfURL: NSURL(string: urlString)!)!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
    print (jsonDict)
}
catch {
    print ("Couldn't get JSON... \(error)")
}

use this Simple code to get a jSon Array

   let data = NSData(contentsOfURL: NSURL(string: "your URL")!)


        let jsonArray: NSArray = try! NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSArray

After that Convert this array to NSDictionary and use its Values.. A sample to convert into Dictionary is

 let cell  = tableView.dequeueReusableCellWithIdentifier("atCell")! as UITableViewCell

        let maindata = (data[indexPath.row] as! NSDictionary)
        cell.textLabel?.text = maindata["date"] as? String

ps I used a table View to show the data...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM