Irfan Saeed
Irfan Saeed

Reputation: 1

How to make Nested JSON in Swift 3

enter image description here

I want to make JSON just like shown in image. On android side it works fine as shown in picture but in Swift i did not know how to make this. Kindly guide me how to make nested JSON in Swift 3. Thanks in advance. Here is my Swift Code.

@IBAction func submitAction(_ sender: Any) {

    let email = pref.value(forKey: "userEmail") as! String

    var myDict = [String: String]()

    var newArray = [NSDictionary]()

    var counter = 0

    for items in emailArray {

       myDict.updateValue(items, forKey: "receiveremail" + "" + String(counter))

        counter += 1

    }


    print("Array \(myDict)")

    let postData = "\"senderemail\":\"\(email)\",\"messageid\":\"\(uuid)\",\"message\":\"\(receiceMsg!)\",\"pic\":\"\(imageString)\", \"meditype\":\"\(mediType!)\",\"emailArray\":\"\(myDict)\""



            let postDat = "jsondata={\(postData)}"

            print("Post Data is \(postDat)")



            let url = URL(string: new_url)

            var doRequest = URLRequest(url: url!)

            doRequest.httpMethod = "POST"

            doRequest.httpBody = postDat.data(using: String.Encoding.utf8)

            doRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
            doRequest.addValue("application/json", forHTTPHeaderField: "Accept")


            let task = URLSession.shared.dataTask(with: doRequest){data, response, error in

                if error != nil {
                    print("Error\(error)")


                    return
                }


                if response != nil{

                    print("response is \(response)")

                }

                let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)

                print("Response String is \(responseString!)")

                do{
                    let json = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
                    print("\(json)")

                }
                catch{
                    print(error.localizedDescription)

                }
            }
            task.resume()
}

here is my JSON that i want to create.

 {
 "senderemail": "[email protected]",
 "messageid": "1de14540-1822-4a1a-923d-824fb713d703",
 "message": "I love Pakistan",
 "pic": "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkz\nODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2Nj\nY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wAARCABQAFADASIA\nAhEBAxEB/8QAHwAAAQUBAQn",
 "meditype": "abundance",
 "emailArray": [
 {
 "receiveremail": "[email protected]"
 },
 {
 "receiveremail": "[email protected]"
 }
 ]
 }

{
[
  "meditype":"Abundance",
  "messageid":"DDDABB40-C8E5-40E4-B1CF-D1A2F1701048",
  "message":"hello",
  "senderemail":"[email protected]",
  "pic":nil,
  "emailArray":[
     [
        "receiveremail":"[email protected]"
     ],
     [
        "receiveremail":"[email protected]"
     ]
  ]
 ]
}

First of All i download data from server and show in myTableView.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let Cell: CreateFriendsCell = myTableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CreateFriendsCell

    Cell.nameLabel.text = friendsArray[indexPath.row].name

    return Cell   
}

then i select the rows and append the selected rows's person's email into array declare globaly as

var myArray = [String]()    

Here is i select cell in tableView

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {


    let cell = tableView.cellForRow(at: indexPath)

    if cell?.accessoryType == UITableViewCellAccessoryType.none {

        cell?.accessoryType = .checkmark

        selectedIndex = friendsArray[indexPath.row].email

        myArray.append(selectedIndex)

}
    else if cell?.accessoryType == UITableViewCellAccessoryType.checkmark {

        cell?.accessoryType  = .none

    }
}

Then i send the selected emails with other some information to the server as below.

@IBAction func submitAction(_ sender: Any) {

    let myEmail = pref.value(forKey: "userEmail") as! String

    var newDict = [String: Any]()


    for email in myArray {

        newDict["receiveremail"] = email

        emailArray.append(newDict as! [String : String])

    }
        let requestBody: [String : Any] =

            [
                "senderemail": myEmail,
                "messageid": uuid,
                "message": receiceMsg!,
                "pic": imageString,
                "meditype": mediType!,
                "emailArray": emailArray

    ]
            let postDat = "jsondata={\(requestBody)}"

            print("Post Data is \(postDat)")

            let url = URL(string: create_intention)

            var doRequest = URLRequest(url: url!)

            doRequest.httpMethod = "POST"

            doRequest.httpBody = postDat.data(using: String.Encoding.utf8)

            doRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
            doRequest.addValue("application/json", forHTTPHeaderField: "Accept")


            let task = URLSession.shared.dataTask(with: doRequest){data, response, error in

                if error != nil {
                    print("Error\(error)")


                    return
                }


                if response != nil{

                    print("response is \(response)")

                }

                let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)

                print("Response String is \(responseString!)")

                do{
                    let json = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
                    print("\(json)")

                }
                catch{
                    print(error.localizedDescription)

                }
            }
            task.resume()
}

when i press the button it prints json like this in console.

{
[
"meditype":"Abundance",
"messageid":"DDDABB40-C8E5-40E4-B1CF-D1A2F1701048",
"message":"hello",
"senderemail":"[email protected]",
"pic":nil,
"emailArray":[
[
    "receiveremail":"[email protected]"
 ],
 [
    "receiveremail":"[email protected]"
 ]
 ]
 ]
 }

But i need this type of JSON.

{
 "senderemail": "[email protected]",
 "messageid": "1de14540-1822-4a1a-923d-824fb713d703",
 "message": "I love Pakistan",
 "pic": "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkz\nODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2Nj\nY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wAARCABQAFADASIA\nAhEBAxEB/8QAHwAAAQUBAQn",
 "meditype": "abundance",
 "emailArray": [
 {
 "receiveremail": "[email protected]"
 },
 {
 "receiveremail": "[email protected]"
 }
 ]
 }

Upvotes: 0

Views: 1517

Answers (2)

laaksom
laaksom

Reputation: 2210

Your top level object should be [String: Any]. You can then add whatever data structures you need as values for the applicable keys.

let emailArray = [[String:Any]]()
//...logic to add items
yourTopLevelObj["emailArray"] = emailArray

Upvotes: 0

Jasveer Singh
Jasveer Singh

Reputation: 374

This should work fine -

    var emailArray:[[String:String]]
    for email in self.youremailarray {
        emailArray.append(["receiveremail": email])
    }

    let requestBody: [String : Any] = ["senderemail": self.email,
                                       "messageid": self.messageId,
                                       "message": self.message,
                                       "pic": self.pic.kClientID,
                                       "meditype": self.meditype,
                                       "emailArray": emailArray]

Upvotes: 1

Related Questions