Upv*_*ote 7 ios swift swifty-json
我有一个用例,我有一个字典数组,我需要它们作为一个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])
Run Code Online (Sandbox Code Playgroud)
第一个印刷声明给了我
[
{"price":"1.20","city":"Foo","_id":"326105","street":"One"},
{"price":"1.20","city":"Bar","_id":"326104","street":"Two"}
]
Run Code Online (Sandbox Code Playgroud)
第二
null
Run Code Online (Sandbox Code Playgroud)
但我希望它能返回json数组中的第一个元素.我做错了什么?
Jef*_*mas 23
根据文档,这应该是你所需要的.
var data = [Dictionary<String, String>]()
//append items
var jsonObj = JSON(data)
println(jsonObj)
println(jsonObj[0])
Run Code Online (Sandbox Code Playgroud)
您是否将数组直接转换为JSON对象?
我不确定你在第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])
Run Code Online (Sandbox Code Playgroud)
......输出......
"[[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]"
Run Code Online (Sandbox Code Playgroud)
编辑:我现在看到swifty-json的标签.我对此并不熟悉,但上面包含的代码与内置方法一起使用.
| 归档时间: |
|
| 查看次数: |
22491 次 |
| 最近记录: |