I try to convert JSON string to a JSON object but after JSONSerialization
the output is nil
in JSON.
Response String:
[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]
I try to convert this string with my code below:
let jsonString = response.result.value let data: Data? = jsonString?.data(using: .utf8) let json = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String:AnyObject] print(json ?? "Empty Data")
An object that converts between JSON and the equivalent Foundation objects.
JSON stands for JavaScript Object Notation. JSON is a lightweight format for storing and transporting data. The JSON format consists of keys and values. In Swift, think of this format as a dictionary where each key must be unique and the values can be strings, numbers, bools, or null (nothing).
The problem is that you thought your jsonString is a dictionary. It's not.
It's an array of dictionaries. In raw json strings, arrays begin with [
and dictionaries begin with {
.
I used your json string with below code :
let string = "[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]" let data = string.data(using: .utf8)! do { if let jsonArray = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [Dictionary<String,Any>] { print(jsonArray) // use the json here } else { print("bad json") } } catch let error as NSError { print(error) }
and I am getting the output :
[["form_desc": <null>, "form_name": Activity 4 with Images, "canonical_name": df_SAWERQ, "form_id": 3465]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With