如何在Swift 2.1中生成jsonDictionary或请求下列格式的主体?

时间:2015-11-16 06:06:27

标签: json post swift2 nsdictionary ios9

enter image description here

OR

enter image description here

我想将上述详细信息发送到API POST正文请求中。请帮助我,我对swift非常新。

更新

我已根据以下解决方案更新了我的代码。但花括号和括号没有正确解决问题?

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以编写如下代码,

    var dict: [String : AnyObject] = ["userId" : "", "shops" : ""]
    var shops: Array<[String: AnyObject]> = []

    var shop : [String:AnyObject] = ["shopId" : "", "categeoryId" : "", "categoryNames": ""]

    let categoryID:Array<String> = ["1210", "1210", "1210"]
    let categoryNames:Array<String> = ["Repair", "RepairTest", "RepairTes3t"]

    shop.updateValue("13", forKey: "shopId")
    shop.updateValue(categoryID, forKey: "categeoryId")
    shop.updateValue(categoryNames, forKey: "categoryNames")

    shops.append(shop)
    dict.updateValue("7", forKey: "userId")
    dict.updateValue(shops, forKey: "shops")
    print(dict)

要发送int POST API,只需序列化它。您可以按如下方式序列化。

 do {
        let jsonData = try NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions.PrettyPrinted)
        let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)! as String
        print(jsonString)
    } catch let myJSONError {
        print(myJSONError)
    }