JSONSerialization code error

I have some problem with this code.
it's print passed 1st and Error JSON!!!

server response :

{"last_modify_time":"2019-02-21 01:12:35"}

My swift codes :

let url = URL(string: "http://swiftapp.saedi/service.php?action=update")
        let session = URLSession.shared
        
        let request = NSMutableURLRequest(url: url!)
        request.httpMethod = "POST"
        request.timeoutInterval = TimeInterval(10)
        
        do{
            let jsonData = try JSONSerialization.data(withJSONObject: dictionary, options: JSONSerialization.WritingOptions(rawValue: 0))
            request.httpBody = jsonData
        }catch{
            print("JSON Error!")
        }
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        
        let task = session.dataTask(with: request as URLRequest) { (nsdata, response, error) in
            
            do{
                print("Passed 1st")
                let dictionary = try JSONSerialization.jsonObject(with: nsdata!, options: JSONSerialization.ReadingOptions.mutableContainers)
                print("Passed 2nd")
                let dic = dictionary as! NSDictionary
                let last_modify_time = dic["last_modify_time"] as! String
                print("Passed 3rd")
                if last_modify_time != ""{
                    
                    for i in 0...(AppDelegate.notes.count - 1){
                        if AppDelegate.notes[i].task_id == self.task_id{
                            DispatchQueue.main.async {
                                AppDelegate.notes[i].task_title = self.edtTaskTitle.text
                                AppDelegate.notes[i].task_desc = self.txtTaskDesc.text
                                AppDelegate.notes[i].task_done = (self.SwitchTaskDone.isOn ? 1 :0)
                            }
                            
                        }
                    }
                    
                    
                    
                    DB.getInstance().executeChange(sqlStr: "UPDATE task SET task_title='\(self.edtTaskTitle.text!)',task_desc='\(self.txtTaskDesc.text!)',task_done='\((self.SwitchTaskDone.isOn ? 1 :0))',last_modify_time='\(last_modify_time)'")
                }else{
                    print("Error Update!")
                    
                }
            }catch{
                
                print("Error JSON!!!")
                
            }

Hello, try this instead:

catch{
    print("Error: \(error)")
}

It will print a detailed error message that will tell you why the JSON decoding has failed. Read it carefully: it will help you understand the error, and find the best solution.

This technique print("Error: \(error)") will generally help you understand errors, not only when decoding JSON. Try it, you'll improve your skills very quickly.

3 Likes

thanks
now i have this problem

Error: Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

Add

print(String(data: nsdata!, encoding: .utf8)"

after

print("Passed 1st")

to see the response data as string. It might not be what you are expecting.

3 Likes

thanks guys fixed :grin::grin:

1 Like
Terms of Service

Privacy Policy

Cookie Policy