如何在 ios swift 中创建 json 对象

Posted

技术标签:

【中文标题】如何在 ios swift 中创建 json 对象【英文标题】:how to create json object in ios swift 【发布时间】:2017-07-17 07:39:02 【问题描述】:

当我在表中插入数据时,我有 3 个数组,而不是数据也添加到数组中(键、值对)。

var person = ["ABC","XYZ","PQR"]
var email = ["abc@yahoo.com","xyz@yahoo.com","pqr@yahoo.com"]
var mobile = ["1234567890","1234567890","1234567890"]

我的问题是如何创建 JSON 对象和数据存储键值对。

我想要这个


    "blogs": [
        
            "person": "ABC",
            "email": "abc@yahoo.com",
            "contact": "1234567890"
        ,
        
            "person": "XYZ",
            "email": "xyz@yahoo.com",
            "contact": "1234567890"
        ,

            "person": "PQR",
            "email": "pqr@yahoo.com",
            "contact": "1234567890"
        
    ]

以便数据传递给url()

在数组和表格中添加数据的动作按钮中

@IBAction func meeting_info(_ sender: Any) 

        var PersonName = person_name.text
        var Email = email_id.text
        var MobileNo = mobile_no.text

        if (person_name.text?.isEmpty)! || (email_id.text?.isEmpty)! || (mobile_no.text?.isEmpty)!  

            displayMyAlertMessage(userMessage: "please check field empty or not");

        

        else

            person.append(person_name.text!)
            email.append(email_id.text!)
            mobile.append(mobile_no.text!)

            meetingTableView.reloadData()

        



    

我想以键值对的形式从人员、电子邮件和联系人生成 JSON 数组

【问题讨论】:

【参考方案1】:

回答你的问题。

 var person = ["ABC","XYZ","PQR"]
    var email = ["abc@yahoo.com","xyz@yahoo.com","pqr@yahoo.com"]
    var mobile = ["1234567890","1234567890","1234567890"]


    var paramCollection = [Any]()

    var index = 0
    for personData in person 
        var dataCollection = [String:Any]()
        dataCollection["person"] = personData
        dataCollection["email"] = email[index]
        dataCollection["contact"] = mobile[index]
        paramCollection.append(dataCollection)
        index += 1
    

    let finalParameter = ["blogs":paramCollection]


//This will do the trick but to make it more robust you should rethink your design
// maybe use struct to store a persons data
struct Blog 
    var person: String
    var email: String
    var mobile: String

    init(name:String, email:String, phone:String) 
        self.person = name
        self.email = email
        self.mobile = phone
    


//and instead of having three arrays holding three different property, you can have one array of
var blogArray = [Blog]()

//You understand where I'm going with this

【讨论】:

【参考方案2】:

选择多个与同一实体的数据相关的数组并不是一个很好的设计。

理想情况下,创建一个名为 Blog 的实体模型,其中包含 personName、email、mobileNo 等字段,如下所示 -

struct Blog 

var personName: String?
var email: String?
var mobileNo: String?

然后在你的代码中有一个这个数组来保存数据然后你可以使用链接直接将它转换成 Json

Convert Custom Structs to Json

【讨论】:

【参考方案3】:

试试这个:

let jsonObject: [String: Any]?
let array: [[String: Any]] = [[:]]

    for i in 0..person.count 
    let dict = ["person": person[i],
        "email": email[i],
        "contact": mobile[i]]
    array.append(dict)
    
    jsonObject = ["blogs": array]

let validateJson = JSONSerialization.isValidJSONObject(jsonObject)
if validateJson 
  //Go Ahead

【讨论】:

我将您的值传递给一个参数,例如 var sss = ["cutomer name":"xyz","date":"13-08-2017","blogs": array] as [String : Any] 并转换为 jsonobject 和该 jsonobject 传递给 post web service.any 未来进程的探针【参考方案4】:
let dictionary = ["key1": "value1", "key2": "value2"] 
let jsonData = try? JSONSerialization.data(withJSONObject: dictionary, options: .prettyPrinted) 
// Verifying it worked: 
let parsedObject = try! JSONSerialization.jsonObject(with: jsonData!, options: .allowFragments)

【讨论】:

以上是关于如何在 ios swift 中创建 json 对象的主要内容,如果未能解决你的问题,请参考以下文章

在 Swift 中创建 JSON 数组

如何使用 Swift 4 在 iOS 9+ 中创建瀑布布局

如何在swift ios中创建指定的数据结构?

如何使用 Swift 在 iOS 应用中创建热点网络

如何在 iOS 编程中在 Swift 中创建实体文件?

Swift Json 连接失败。 JSON对象正确吗?