NSDictionary>使用SwiftyJSON的JSON字符串

时间:2015-10-29 01:45:30

标签: swift nsdictionary swifty-json

这就是我正在做的转换它。日志返回nil

let keys = ["firstName", "lastName", "age","carNumber", "licenseNumber", "email","password", "msgType"]
let objects = ["Pencil", "Eraser", "2332","534543", "543543", "Notebook","Pencil", "ADD_DRIVER"]
self.dictionary = NSDictionary(objects: objects, forKeys: keys)

var data = [Dictionary<String, String>]()
data.append(self.dictionary as! Dictionary<String, String>);
var jsonObj = JSON(data)

print("JSON Object")
print(jsonObj.stringValue)

2 个答案:

答案 0 :(得分:7)

要使用SwiftyJSON创建JSON字符串,请使用rawString(encoding: UInt = default, options opt: NSJSONWritingOptions = default)。这样字符串就不会包含新行等无效字符。

字典示例:

let keys = ["firstName", "lastName", "age","carNumber", "licenseNumber", "email","password", "msgType"]
let objects = ["Pencil", "Eraser", "2332","534543", "543543", "Notebook","Pencil", "ADD_DRIVER"]
let dict = NSDictionary(objects: objects, forKeys: keys)
let jsonObj = JSON(dict)
if let stringJSON = jsonObj.rawString(NSUTF8StringEncoding, options: []) {
    print(stringJSON)
}

结果:

  

{ “姓氏”: “橡皮擦”, “密码”: “铅笔”, “年龄”: “2332”, “名字”: “铅笔”, “licenseNumber”: “543543”, “电子邮件”:“笔记本”, “carNumber”: “534543”, “MSGTYPE”: “ADD_DRIVER”}

如果您想要在编码为JSON字符串之前在数组中使用它,那么只需将其嵌入到这样的数组中:

let keys = ["firstName", "lastName", "age","carNumber", "licenseNumber", "email","password", "msgType"]
let objects = ["Pencil", "Eraser", "2332","534543", "543543", "Notebook","Pencil", "ADD_DRIVER"]
let dict = NSDictionary(objects: objects, forKeys: keys)
let jsonObj = JSON([dict])
if let stringJSON = jsonObj.rawString(NSUTF8StringEncoding, options: []) {
    print(stringJSON)
}

结果:

  

[{ “MSGTYPE”: “ADD_DRIVER”, “密码”: “铅笔”, “名字”: “铅笔”, “年龄”: “2332”, “电子邮件”: “笔记本”, “carNumber”:” 534543" , “licenseNumber”: “543543”, “姓氏”: “橡皮擦”}]

答案 1 :(得分:1)

这就是我提交RESTful API的方式:

let submitJson: JSON =  ["user": username, "pass": password]
self.body = submitJson.rawString()!

print(self.body)返回:

{   &#34;通过&#34; :&#34; xxx&#34;,   &#34;用户&#34; :&#34; xxx&#34; }