0

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]"
 }
 ]
 }
3
  • Possible duplicate of Create JSON in swift Commented Jul 12, 2017 at 12:39
  • @eshirima its different question and not duplicate. Its get multiple email in nested array and i am unable how to do this. Commented Jul 12, 2017 at 12:43
  • 1
    The point of duplicate flags is to say that the context of the asked question already has been answered before. The provided link is meant to be a guide for you to see how to create JSON in Swift then take it from there. All you have to do to get your desired result is map your array to a key of your desire. Commented Jul 12, 2017 at 13:00

2 Answers 2

1

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]
Sign up to request clarification or add additional context in comments.

4 Comments

When i apply this i got a different JSON as shown below. But i want JSON as post in my question.
can you copy paste the complete code to check what you are doing wrong?
See below my full scenario and guide me accordingly. Thank you very much for this act.
try to send the request it should work fine, I just tested it. You are doing something else wrong in the code. I am here to help you not to do the coding for you.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.