I am trying to convert my swift struct to json format. There seems to be quite a few questions like this, but none of the solutions has worked for me so far.
Here is my struct
struct Rec : Codable {
var name:String
var time:Int
var values:[String]
var jsonRepresentation : String {
return """
{
"name":"\(name)",
"time":\(time),
"values":\(values)
}
"""
}
}
Here is the json format that the external api recieves.
{
"op" : "delete",
"rec": {
"name" : "some string",
"time":200,
"values": [
"127.0.0.1"
]
}
}
Here is my function the creates the HTTP request
private func createPatchRequest(op: String, url: URL, rec: Rec) throws -> URLRequest {
let dictionary: [String: String] = [
"op":op,
"rec":rec.jsonRepresentation
]
let jsonData = try JSONEncoder().encode(dictionary)
var request = URLRequest(url: url)
request.httpMethod = "PATCH"
request.httpBody = jsonData
request.addValue("application/json", forHTTPHeaderField:"Content-Type")
return request
}
I always get a 400 and i believe that swift isn't' encoding my json properly. I tried the request on postman and it worked fine!
Here is how it looked on postman
{
"op" : "delete",
"rec": {
"name" : "some string",
"time":600,
"values": [
"127.0.0.1"
]
}
}
Any ideas? Thanks!
Codable, you don't have to do the weird manually createdjsonRepresentationthing and then encode it, you can just directly callJSONEncoder().encode(rec). You would need to create a wrapper request struct that hadopandrecproperties and encode that one though