【问题标题】:NSDictionary to json string to json object using SwiftyJSONNSDictionary to json string to json object using SwiftyJSON
【发布时间】:2015-01-07 10:08:05
【问题描述】:

我有一个用例,我有一个字典数组,我需要它们作为 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])

第一个打印语句给了我

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

第二个

null

但我希望它返回 json 数组中的第一个元素。我做错了什么?

【问题讨论】:

  • 我对 Swifty JSON 一无所知,但我推测jsonObj 是一个对象,其description 显示您看到的数据。但是对象不是数组,[0] 操作符会反弹。

标签: ios swift swifty-json


【解决方案1】:

根据文档,这应该就是您所需要的。

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

println(jsonObj)
println(jsonObj[0])

您在将数组直接转换为JSON 对象时遇到问题吗?

【讨论】:

    【解决方案2】:

    我不确定你在第 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])
    

    ...带输出...

    "[[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]"
    

    编辑:我现在看到了 swifty-json 的标签。我对此并不熟悉,但我上面包含的代码适用于内置方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-01
      • 2021-07-26
      相关资源
      最近更新 更多