Swift 4 Decodable: data is invalid JSON

I am trying to write a POST request to my local server, this is my function:

@IBAction func postButtonAction(_ sender: UIButton) { guard let url = URL(string:"http://localhost:443/api/message") else {return} var request = URLRequest(url: url) request.httpMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") print("POSTED") let date : Date = Date() let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" let dateTime = dateFormatter.string(from: date) let newPost = MessageForPost(message: "Hi", timestamp: dateTime, latitude: "1.1", longitude: "2.2") let newData = DataForPost(message: newPost) let newPackage = PackageForPost(data: newData) do { let jsonBody = try JSONEncoder().encode(newPackage) request.httpBody = jsonBody print("jsonBody:",jsonBody) let jsonBodyString = String(data: jsonBody, encoding: .utf8) print("JSON String : ", jsonBodyString!) } catch let err { print("jsonBody Error: ",err) } let session = URLSession.shared let task = session.dataTask(with: request){ (data,response,err) in guard let data = data else {return} do{ let sendPost = try JSONDecoder().decode(PackageForPost.self, from: data) print("DATA:\(data)") }catch let err{ print("Session Error: ",err) } } task.resume() } 

Here are the structures that are used here:

 struct PackageForPost:Encodable, Decodable{ let data: DataForPost } struct DataForPost:Encodable, Decodable{ let message: MessageForPost } struct MessageForPost:Codable { let message: String let timestamp: String let latitude: String let longitude: String } 

And he was able to print

 JSON String : {"data":{"message":{"message":"Hi","timestamp":"2017-10-18 00:50:13","latitude":"1.1","longitude":"2.2"}}} 

But he continues to show this ERROR:

Session error: dataCorrupted (Swift.DecodingError.Context (codingPath: [], debugDescription: "Data is not valid JSON.", BasicError: Optional (Error Domain = NSCocoaErrorDomain Code = 3840 "The JSON text did not start with an array or object and an option to allow fragments not set. "UserInfo = {NSDebugDescription = JSON text was not started with an array or object and parameter to allow fragments.})))

Why is this not valid JSON ???

Here is my POST API API request for server:

 POST /api/message { data: { message: { message: "Hey, a new message!", timestamp: 2017-09-10 10:22:33, latitude: 62.233589156441724, longitude: 25.735066461654696 } } } 

I made quite a few search robots, but got stuck here for a very long time! Any help appreciated!

+9
source share
1 answer

It was just .. I had the same problem ..

See that your structure decodes and encodes the timestamp, latitude and longitude, since strings and JSON are of type Double or Floating.

 struct MessageForPost:Codable { let message: String let timestamp: String let latitude: String let longitude: String } 

And here is Json

 { data: { message: { message: "Hey, a new message!", timestamp: 2017-09-10 10:22:33, latitude: 62.233589156441724, longitude: 25.735066461654696 } } } 

.... I fixed it at my end and ... it worked ..

Edited to use the same data type ..

+1
source

Source: https://habr.com/ru/post/1272718/


All Articles