NSJSONSerialization.JSONObjectWithData返回空值

3
[
    {
        "_id": "557f27522afb79ce0112e6ab",
        "endereco": {
            "cep": "asdasd",
            "numero": "asdasd"
        },
        "categories": [],
        "name": "teste",
        "hashtag": "teste"
    }
]

不带错误返回nil:

var json = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.AllowFragments, error: &erro) as? NSDictionary

顺便说一下,NSJSONReadingOptions.AllowFragments 是不必要的。你可以直接使用 nil - Rob
2个回答

4

由于条件类型转换生成的对象不是字典,所以它会返回nil而没有错误。这并不是JSON解析失败了,而是因为JSON不代表一个字典:它是一个有一个元素(恰好是一个字典)的数组。外层的[]表示一个数组。因此,当你解析它时,你需要将它强制类型转换为NSArray

例如,在Swift 1.2中,你可以这样做:

if let json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error) as? NSArray, let dictionary = json.firstObject as? NSDictionary {
    println(dictionary)
} else {
    println(error)
}

或者您可以将其转换为字典数组:

if let json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error) as? [[String: AnyObject]], let dictionary = json.first {
    println(dictionary)
} else {
    println(error)
}

0

调用 isValidJSONObject: 或尝试转换是确定给定对象是否可转换为 JSON 数据的明确方法。

isValidJSONObject(_:) 返回一个布尔值,指示给定对象是否可以转换为 JSON 数据。

声明 SWIFT class func isValidJSONObject(_ obj: AnyObject) -> Bool 参数 obj 要测试的对象。 返回值 如果 obj 可以转换为 JSON 数据,则为 true;否则为 false。

讨论 可用性 在 iOS 5.0 及更高版本中可用。


你应该在回答中提供一个例子。谢谢。 - Hazonko

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接