I am working on this issue since days.
I need to send an object as paramenter to an api endpoint. Is expected to me to send a JSON array of objects with this format.
[
{name:"SomeName", lastname:"Some LastName", address:"watheaver"},
{name:"AnotherName", lastname:"Some LastName", address:"watheaver"},
{name:"AnyName", lastname:"Some LastName", address:"watheaver"}
]
I already have the object parsed to JSON ussing a swift library called "JSONCODABLE" or similar, however if I make an array of those objects and try to serialize the array to JSON I get the error (I dont get any error serializing only the object)
example code
let tratamientos:NSArray = [try! tratamiento.toJSON() as! JSONObject]
let tratamientosArray = try! NSJSONSerialization.dataWithJSONObject(tratamientos, options: []) --> error: Invalid top.level type in JSON write.
What I do next with NSData...
let request = NSMutableURLRequest(URL: NSURL(string: url.SYNC_TRATAMIENTOS)!)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue(auth["UUID"], forHTTPHeaderField: "UUID")
request.HTTPBody = tratamientosArray
Can you please help me figure it out...
Note: I have reads several post regarding how to parse JSONArrayData to array but not the other way around.
###### editafter doing a lot of testing here you have my findings .
//VALID JSON OBJECT I CAN SEND IT TO AN API
let tratamientos = try! tratamiento.toJSON() as! JSONObject
let tratamientos = try! tratamiento.toJSON() as! JSONObject
INVALID OBJECT ALWAYS SENDING NIL NOT GIVING ANY ERROR
let tratamientos = [try! tratamiento.toJSON() as! JSONObject]
let tratamientos = try! tratamiento.toJSON() as! JSONObject
The only diference is the array closure. The object that I want to be contained in an array have arrays also... I can parse that object so I can parse a class or struc that have only one parameter type array but as I am not the owner of the api endpoint I cannot change its structure and I need to send a JSON array like this
[
{one:1},
{two:2},
{thre:3}
]
insted of this
{ numbers:[
{one:1},
{two:2},
{thre:3}]
}
How can I send an array like this instead of an object