简体   繁体   English

NSDictionary使用SwiftyJSON将JSON字符串转换为JSON对象

[英]NSDictionary to json string to json object using SwiftyJSON

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. 但我希望它返回json数组中的第一个元素。 What I am doing wrong? 我做错了什么?

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对象时遇到问题吗?

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: 我不确定第四行(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. 编辑:我现在看到swifty-json的标签。 I'm not familiar with that, but the code I included above works with the built in methods. 我对此并不熟悉,但是上面包含的代码可以与内置方法一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM