Saswat Raj Pandey
Saswat Raj Pandey

Reputation: 75

How to convert the given dictionary into a JSON Object containing a JSON Array In Swift?

I am really new to swift and was having trouble converting the dictionary I have into a JSON that is accepted by the api I am calling.

I have already created a dictionary with the relevant data and am converting it to JSON.

example:---

let requestbody = ["content": ["app_version_name": , "device_locale": , "device_model": , "device_id": , "os_run_time": , "device_time_zone": , "__type": "", "device_type": , "os_build_type": , "installation_id": "", "cloud_version": , "os_version": , "app_package_name": ]]

let jsonData = try? JSONSerialization.data(withJSONObject: requestBody)
let convertedString = String(data: jsonData!, encoding: String.Encoding.utf8)

But while printing the convertedString i am getting:

{
  "content": {
"installation_id": "",
"device_type": "",
"device_id": "",
"device_model": "",
"device_time_zone": "",
"cloud_version": "",
"os_run_time": "",
"device_locale": "",
"app_version_name": "",
"app_package_name": "",
"os_build_type": "",
"os_version": "",
"__type": ""
  }
}

The result I am expecting is

{
  "content": [
{
"installation_id": "",
"device_type": "",
"device_id": "",
"device_model": "",
"device_time_zone": "",
"cloud_version": "",
"os_run_time": "",
"device_locale": "",
"app_version_name": "",
"app_package_name": "",
"os_build_type": "",
"os_version": "",
"__type": ""
    }
 ]
}

Basically I need help in placing the values of content inside a jsonArray.

Upvotes: 1

Views: 41

Answers (1)

Rengers
Rengers

Reputation: 15238

Just wrap your entire content structure inside another array:

let content = ["app_version_name": "", "device_locale": "", "device_model": "", "device_id": "", "os_run_time": "", "device_time_zone": "", "__type": "", "device_type": "", "os_build_type": "", "installation_id": "", "cloud_version": "", "os_version": "", "app_package_name": ""]
let requestbody = ["content": [content]]

Upvotes: 3

Related Questions