【发布时间】:2017-07-12 12:31:10
【问题描述】:
我想制作如图所示的 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"
}
]
}
【问题讨论】:
-
Create JSON in swift的可能重复
-
@eshirima 是不同的问题,而不是重复的。它在嵌套数组中收到多封电子邮件,我无法做到这一点。
-
重复标志的意思是说所问问题的上下文已经被回答过。提供的链接旨在指导您了解如何在 Swift 中创建 JSON,然后从那里获取它。要获得所需的结果,您所要做的就是将您的数组映射到您想要的键。