如何使用swiftyjson获取JSON的值

时间:2016-11-01 18:15:30

标签: json swift swifty-json

我有这个JSON

{
  "chatUsers":"[
    {"id":"5","sender_id":"6","receiver_id":"1","content":"hi","datetime":"2016-11-19 00:00:00"},
    {"id":"4","sender_id":"1","receiver_id":"2","content":"hello","datetime":"2016-11-11 00:00:00"},
    {"id":"2","sender_id":"1","receiver_id":"3","content":"how are you","datetime":"2016-11-04 00:00:00"}
  ]",
  "chatsCount":3
}

现在我有了这段代码来从网址获取数据:

let StringUrl  = NSURL(string: url) as NSURL!
let Data = NSData(contentsOfURL: StringUrl) as NSData!
let ReadableData = JSON(data: Data)

let result =  ReadableData["chatUsers"][0]["id"].string! as String // this should gives 5

但它总是会出现此错误:

  

致命错误:在解包可选值时意外发现nil

任何想法为什么?

1 个答案:

答案 0 :(得分:1)

您在上面提供的示例中存在相当大的错误,但为了让您朝着正确的方向前进,请让我给您一些建议并快速解决您的问题。

首先,不要用大写字符开始变量。它不是一套规则或任何东西,但使用camelCase是更好的做法,因为它会使你的代码更具可读性并避免混淆。

其次,你正在进行大量的强制转换并强制展开可选值,这会使你的应用程序容易崩溃,因为你现在得到了同样的错误。我会看一下以下内容以获得更好的指导:https://stackoverflow.com/a/25195633/4660602

第三,在发布SO时,请确保明确提供问题上下文,因为有些用户可能会认为您在询问optionals是什么以及为什么会出现fatal error: unexpectedly found nil while unwrapping an Optional value错误。

有了这个说法,将来请务必查看SwiftyJSON文档,因为它们非常清楚地演示了如何使用该库。您的代码无法正常工作的原因是您正在错误地处理JSON。这是一个更新的例子:

    let StringUrl  = NSURL(string: url) as NSURL!
    let Data = NSData(contentsOfURL: StringUrl) as NSData!
    let ReadableData = JSON(data: Data)
    let chatUsers = ReadableData["chatUsers"].arrayValue
    let result =  chatUsers[0]["id"].stringValue

或者如果您需要遍历所有用户:

    let StringUrl  = NSURL(string: url) as NSURL!
    let Data = NSData(contentsOfURL: StringUrl) as NSData!
    let ReadableData = JSON(data: Data)

    for chatUser in ReadableData["chatUsers"]{
        print(chatUser.1["id"].stringValue)
    }

请注意,为了不让您感到困惑,我没有将您的变量标识符更新为正确的约定,但您应该遵循我在第一点中提到的正确约定。

祝你好运。

编辑:忘记提及您的JSON格式不正确。请将您的JSON数据修复为正确的JSON格式,以便SwiftyJSON可以正确解释它。您正在接收索引超出范围,因为SwiftyJSON不知道chatUsers是一个数组,因为方括号在它们不应该用双引号括起来时。所以

"chatUsers":"[
{"id":"5","sender_id":"6","receiver_id":"1","content":"hi","datetime":"2016-11-19 00:00:00"},
{"id":"4","sender_id":"1","receiver_id":"2","content":"hello","datetime":"2016-11-11 00:00:00"},
{"id":"2","sender_id":"1","receiver_id":"3","content":"how are you","datetime":"2016-11-04 00:00:00"}
]" 

应该是

"chatUsers": [
{"id":"5","sender_id":"6","receiver_id":"1","content":"hi","datetime":"2016-11-19 00:00:00"},
{"id":"4","sender_id":"1","receiver_id":"2","content":"hello","datetime":"2016-11-11 00:00:00"},
{"id":"2","sender_id":"1","receiver_id":"3","content":"how are you","datetime":"2016-11-04 00:00:00"}
]