如何在Swift 3中制作嵌套JSON

时间:2023-01-22 22:54:10

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.

我想制作JSON就像图像中所示。在android方面,它工作得很好,如图所示,但在Swift我不知道如何做到这一点。请指导我如何在Swift 3中制作嵌套的JSON。提前感谢。这是我的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.

这是我要创建的JSON。

 {
 "senderemail": "usman.ahmed951@gmail.com",
 "messageid": "1de14540-1822-4a1a-923d-824fb713d703",
 "message": "I love Pakistan",
 "pic": "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkz\nODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2Nj\nY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wAARCABQAFADASIA\nAhEBAxEB/8QAHwAAAQUBAQn",
 "meditype": "abundance",
 "emailArray": [
 {
 "receiveremail": "shahryar.aziz.bhutta@gmail.com"
 },
 {
 "receiveremail": "mtm1_r@hotmail.com"
 }
 ]
 }

{
[
  "meditype":"Abundance",
  "messageid":"DDDABB40-C8E5-40E4-B1CF-D1A2F1701048",
  "message":"hello",
  "senderemail":"mtm1_r@hotmail.com",
  "pic":nil,
  "emailArray":[
     [
        "receiveremail":"jsheikh27@yahoo.com"
     ],
     [
        "receiveremail":"shahryar.aziz.bhutta@gmail.com"
     ]
  ]
 ]
}

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

首先,我从服务器下载数据并在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

这是我在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.

当我按下按钮时,它会在控制台中打印这样的json。

{
[
"meditype":"Abundance",
"messageid":"DDDABB40-C8E5-40E4-B1CF-D1A2F1701048",
"message":"hello",
"senderemail":"mtm1_r@hotmail.com",
"pic":nil,
"emailArray":[
[
    "receiveremail":"jsheikh27@yahoo.com"
 ],
 [
    "receiveremail":"shahryar.aziz.bhutta@gmail.com"
 ]
 ]
 ]
 }

But i need this type of JSON.

但我需要这种类型的JSON。

{
 "senderemail": "usman.ahmed951@gmail.com",
 "messageid": "1de14540-1822-4a1a-923d-824fb713d703",
 "message": "I love Pakistan",
 "pic": "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkz\nODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2Nj\nY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wAARCABQAFADASIA\nAhEBAxEB/8QAHwAAAQUBAQn",
 "meditype": "abundance",
 "emailArray": [
 {
 "receiveremail": "shahryar.aziz.bhutta@gmail.com"
 },
 {
 "receiveremail": "mtm1_r@hotmail.com"
 }
 ]
 }

2 个解决方案

#1


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]

#2


0  

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

您的*对象应该是[String:Any]。然后,您可以添加所需的任何数据结构作为适用键的值。

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

#1


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]

#2


0  

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

您的*对象应该是[String:Any]。然后,您可以添加所需的任何数据结构作为适用键的值。

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