0

I'm building parameters to send it to a server. So I need to transform my array of custom object to JSON.

tried this:

let data = try? JSONSerialization.data(withJSONObject: fastForm.route, options: .prettyPrinted)
let str = String(bytes: data!, encoding: .utf8)!

Getting error from the server Invalid supplied for each()

edited: fastForm.route is array of object Route -> [Route]

struct Route: Codable {
    var latitude: String
    var longitude: String
    var waitingMinutes: String!
    var description: String!
}
Artyom
  • 371
  • 1
  • 4
  • 14
  • can you mention what is the type of fastFrom.route? – Jaydeep Vora Jul 30 '19 at 09:37
  • 3
    Get rid of `!` in property declarations, if they need to be able to be `nil` make them a normal optionals – mag_zbc Jul 30 '19 at 09:41
  • 1
    @mag_zbc, indeed, only way where it's acceptable to use `IUO`(!) it's when you have late init property in your class. Otherwise: *just use either proper optional, or non-optional*. – user28434'mstep Jul 30 '19 at 09:49

1 Answers1

0

You can send a json to a server using the following structure

struct Route: Codable {
var latitude: String
var longitude: String
var waitingMinutes: String!
var description: String!

private enum CodingKeys: String, CodingKey {
    case latitude
    case longitude
    case waitingMinutes
    case description
}
}

func encodeData() -> Data? {
    let routes = [Route]()
    guard let data  = try? JSONEncoder().encode(routes) else { return nil }
    return data
}

Then you can put your encoded Data inside the httpBody from your URLRequest.

Ramon Vasconcelos
  • 1,466
  • 1
  • 21
  • 28
  • Getting crash. Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (Foundation.__NSSwiftData)' This is my request: Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { response in print(response) } – Artyom Jul 30 '19 at 11:30
  • This has to be inside the httpBody since you're using a post request. You can follow this reference https://stackoverflow.com/a/28552198/4816590 – Ramon Vasconcelos Jul 30 '19 at 11:39