"Invalid top-level type in JSON write"

I have seen posts about this error message but i am making a new one because my case is different. the json is valid. so i have no clue why it gives out this error.

Sample json here

i removed the forward slash so it will be clean since when i do a print() it always shows as "key": "value"

this is the code i use to convert it to data then it gives out that error. i checked the json in online json validator sites and it's good.

let string = the json string from the url above
let jsonObject = try? JSONSerialization.data(withJSONObject: string, options: [])

It is supposed to be a json array. any idea why the error?

this is irritating. I cant post a json sample even though i already trimmed it

Accepted Answer

That’s not the right API. You want the one that goes the other direction: JSONSerialization.jsonObject(with:options:). The term “JSON object” in this API means data structures in your app that can be converted to/from JSON: arrays, dictionaries, strings, numbers, etc.

Having said that, I’d strongly recommend you consider the modern Swift API for JSON: JSONDecoder (link) and the Codable protocol. The very old JSONSerialization is fine for Objective-C but isn’t a good choice when writing new code in Swift.

"Invalid top-level type in JSON write"
 
 
Q