Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Json string to Json object in Swift 4

Tags:

ios

swift

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") 
like image 696
Inderpal Singh Avatar asked Nov 14 '17 08:11

Inderpal Singh


People also ask

What is Jsonserialization in Swift?

An object that converts between JSON and the equivalent Foundation objects.

What is JSON in Swift 4?

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).


1 Answers

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]] 
like image 199
Amit Avatar answered Oct 04 '22 14:10

Amit