gpt4 book ai didi

ios - 如何在 Swift 3 中制作嵌套的 JSON

转载 作者:行者123 更新时间:2023-11-28 15:27:25 24 4
gpt4 key购买 nike

enter image description here

我想制作如图所示的 JSON。如图所示,在 android 端它工作正常,但在 Swift 中我不知道如何制作它。请指导我如何在 Swift 3 中制作嵌套的 JSON。提前致谢。这是我的 Swift 代码。

@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()
}

这是我要创建的 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"
]
]
]
}

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

然后我选择行并将所选行的人员的电子邮件附加到数组中,全局声明为

var myArray = [String]()    

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

}
}

然后我将选定的电子邮件和其他一些信息发送到服务器,如下所示。

@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()
}

当我按下按钮时,它会在控制台中打印出这样的 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"
]
]
]
}

但我需要这种类型的 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"
}
]
}

最佳答案

这应该可以正常工作 -

    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]

关于ios - 如何在 Swift 3 中制作嵌套的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45057773/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com