ios 使用 SwiftyJSON 将 NSDictionary 转换为 json 字符串到 json 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26855074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NSDictionary to json string to json object using SwiftyJSON
提问by Upvote
I have a use case where I have an array of dictionaries and I need them as a json object:
我有一个用例,我有一个字典数组,我需要它们作为 json 对象:
var data = [Dictionary<String, String>]()
//append items
var bytes = NSJSONSerialization.dataWithJSONObject(data, options: NSJSONWritingOptions.allZeros, error: nil)
var jsonObj = JSON(NSString(data: bytes!, encoding: NSUTF8StringEncoding)!)
println(jsonObj)
println(jsonObj[0])
The first print statement gives me
第一个打印语句给了我
[
{"price":"1.20","city":"Foo","_id":"326105","street":"One"},
{"price":"1.20","city":"Bar","_id":"326104","street":"Two"}
]
the second
第二
null
but I would expect it to return the first element in the json array. What I am doing wrong?
但我希望它返回 json 数组中的第一个元素。我做错了什么?
回答by Jeffery Thomas
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?
您是否在将数组直接转换为JSON
对象时遇到问题?
回答by 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:
我不确定你在那里的第 4 行(JSON)有什么方法,但我让你的代码使用NSJSONSerialization.JSONObjectWithData
如下所示:
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.
编辑:我现在看到了 swifty-json 的标签。我对此并不熟悉,但我上面包含的代码适用于内置方法。