NSDictionary to json string to json object using SwiftyJSON

老子叫甜甜 提交于 2019-12-03 08:22:18

According to the docs, this should be all you need.

var data = [Dictionary<String, String>]()
//append items 
var jsonObj = JSON(data)

println(jsonObj)
println(jsonObj[0])

Are you having a problem with converting an array directly into a JSON object?

Acey

I'm not sure what method you have on the 4th line there (JSON) but I got your code to work using NSJSONSerialization.JSONObjectWithData seen below:

var data = [Dictionary<String, String>]()
data.append(["price":"1.20","city":"Foo","_id":"326105","street":"One"])
data.append(["price":"1.20","city":"Bar","_id":"326104","street":"Two"])

let bytes = try! NSJSONSerialization.dataWithJSONObject(data, options: NSJSONWritingOptions.PrettyPrinted)
var jsonObj = try! NSJSONSerialization.JSONObjectWithData(bytes, options: .MutableLeaves) as! [Dictionary<String, String>]

print(jsonObj)
print(jsonObj[0])

... with output ...

"[[price: 1.20, city: Foo, _id: 326105, street: One], [price: 1.20, city: Bar, _id: 326104, street: Two]]"

"[price: 1.20, city: Foo, _id: 326105, street: One]"

Edit: I see now the tag for swifty-json. I'm not familiar with that, but the code I included above works with the built in methods.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!