在Swift / iOS中解析JSON响应

时间:2016-05-25 20:25:52

标签: json swift nsarray

我有以下JSON。

[{"chatId":"1","user1_id":"1212","user2_id":"8543211123","user1_name":"dave","user2_name":"daveee","user1_profile_pic":"http:\/\/graph.facebook.com\/1212\/picture?type=large","user2_profile_pic":"https:\/\/scontent-waw1-1.xx.fbcdn.net\/v\/t1.0-9\/1212.jpg?oh=c288ac7b31a61aee751e8ddafb05e78a&oe=57DC702E","message":{"1":{"message_id":"24242241","sender":"1212","chatId":"1","text":"hello i am","timestamp":"2016-05-24 17:13:08"},"2":{"message_id":"421421","sender":"1212","chatId":"1","text":"great","timestamp":"2016-05-24 17:15:08"}}},{"chatId":"2","user1_id":"23413524635","user2_id":"1212","user1_name":"Leo","user2_name":"dave","user1_profile_pic":"https:\/\/scontent-fra3-1.xx.fbcdn.net\/v\/l\/t1.0-1\/1212.jpg?oh=1212&oe=579AE3AE","user2_profile_pic":"http:\/\/graph.facebook.com\/1212\/picture?type=large","message":{"1":{"message_id":"21321213","sender":"1212","chatId":"2","text":"yes, hi","timestamp":"2016-05-25 15:46:57"}}}]

我想遍历message并为每个计数器提取值。这是我的代码:

for anItem in jsonArray as! [Dictionary<String, AnyObject>]
var chat_messages : [Message]? = nil
var count_messages = 0;
if let dataArray = anItem["message"] as? [Int : Dictionary<String, AnyObject> ] {
    for onemessage in dataArray as! [Dictionary<String, AnyObject>] {
        let curr_message = Message()
        if let messageid = onemessage["message_id"] as? String {
            curr_message.id =  messageid
        }
        if let messagedate = onemessage["timestamp"] as? NSDate {
            curr_message.date = messagedate
        }
        if let messagesender = onemessage["sender"] as? String {
            curr_message.sender = messagesender
        }
        if let messagetext = onemessage["text"] as? String {
            curr_message.text = messagetext
        }
        chat_messages![count_messages] = curr_message
        count_messages = count_messages + 1
    }
}

问题是,行if let dataArray = anItem["message"] as? [Int : Dictionary<String, AnyObject> ] {始终失败,并且永远不会输入if条件。

1 个答案:

答案 0 :(得分:2)

如果您使用的是NSJSONSerialization,那么每个字典的类型都是:[String : AnyObject]。所以这一行:

if let dataArray = anItem["message"] as? [Int : Dictionary<String, AnyObject> ] {

应该是:

if let dataArray = anItem["message"] as? [String : AnyObject] {

要遍历dataArray内的消息词典,您可以替换:

for onemessage in dataArray as! [Dictionary<String, AnyObject>] {

使用:

for (_, messageDictionary) in dataArray {
    if let onemessage = messageDictionary as? [String : AnyObject] {

以及从onemessage词典中获取各种值的其余代码应该可以正常编写,除非此行会崩溃:

chat_messages![count_messages] = curr_message

因为你被迫展开chat_messages,你初始化为nil:

var chat_messages : [Message]? = nil

而不是空数组:

var chat_messages = [Message]()