【问题标题】:Extracting data from NSArray从 NSArray 中提取数据
【发布时间】:2026-01-23 02:35:02
【问题描述】:

我的 php 脚本以如下所示的格式向我的 swift iOS 应用程序发送 JSON 响应。使用以下代码将其解析为NSArray

let jsonArray = try NSJSONSerialization.JSONObjectWithData(data_fixed!, options:[])

我在我的 swift 代码中创建了以下对象:

class Friend : NSObject {
var name: String?
var id: String?
var profile_pic : String?


}


class Message : NSObject {
var id: String?
var text: String?
var date: NSDate?
var sender: Friend?
}

class Chat : NSObject {
var id : String?
var chat_partner : Friend?
var chat_messages : [Message]?
}

我现在要做的是循环遍历下面的NSArray,并将数据提取到我的对象的实例中,所以用下面的例子简单来说,我想创建两个 id 为 1 和 2 的聊天对象,以及所有适当的变量。我不确定如何快速正确地执行这样的循环。

JSON 响应:

Array: (
    {
    chatId = 1;
    message =         {
        1 =             {
            chatId = 1;
            "message_id" = 24242241;
            sender = 1233;
            text = "hello i am";
            timestamp = "2016-05-24 17:13:08";
        };
        2 =             {
            chatId = 1;
            "message_id" = 421421;
            sender = 1233;
            text = great;
            timestamp = "2016-05-24 17:15:08";
        };
    };
    "user1_id" = 1233;
    "user1_name" = David;
    "user1_profile_pic" = "http://graph.facebsddsaadsadsook.com/1233/picture?type=large";
    "user2_id" = 8543211123;
    "user2_name" = 0;
    "user2_profile_pic" = "<null>";
},
    {
    chatId = 2;
    "user1_id" = 23413524635;
    "user1_name" = 0;
    "user1_profile_pic" = "<null>";
    "user2_id" = 1233;
    "user2_name" = David;
    "user2_profile_pic" = "http://graph.facebsdadsook.com/1233/picture?type=large";
}
)

更新:代码尝试

                        var count_chats = 0;
                       for anItem in jsonArray as! [Dictionary<String, AnyObject>] {
                            let curr_chat = Chat()
                            if let chatId = anItem["chatId"] as? String {
                                curr_chat.id = chatId
                            }
                            let friend = Friend()
                            let user1id = anItem["user1_id"] as! String
                            let user2id = anItem["user2_id"] as! String
                            if (user1id == userID) {
                                if let user2id = anItem["user2_id"] as? String {
                                    friend.id = user2id
                                }
                                if let user2name = anItem["user2_name"] as? String {
                                    friend.name = user2name
                                }
                                if let user2profilepic = anItem["user2_profile_pic"] as? String {
                                    friend.profile_pic = user2profilepic
                                }
                            }
                            else if (user2id == userID){
                                if let user1id = anItem["user1_id"] as? String {
                                    friend.id = user1id
                                }
                                if let user1name = anItem["user1_name"] as? String {
                                    friend.name = user1name
                                }
                                if let user1profilepic = anItem["user1_profile_pic"] as? String {
                                    friend.profile_pic = user1profilepic
                                }
                        }
                            print("passed")
                                curr_chat.chat_partner = friend


                            var chat_messages : [Message]? = nil
                            var count_messages = 0;
                            if let dataArray = anItem["message"] as? NSArray {
                                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
                                }
                            }

                            curr_chat.chat_messages = chat_messages
                            self.user_chats![count_chats] = curr_chat
                            count_chats = count_chats + 1

【问题讨论】:

  • 所以试一试吧。您来自 JSON 的数据将以 AnyObject 类型输入。您需要将其转换为类型 [NSDictionary]。然后,您需要从每个字典条目中获取键/值对,将它们的值转换为适当的类型,并构建您的自定义对象数组。如果您遇到困难,请在此处发布您的代码,我们会帮助您调试它,但我们不会为您编写代码。
  • @DuncanC 我已经用代码尝试更新了我的问题,请你看看并告诉我我的方法是否正确
  • 不,这不是它的工作原理。您将该代码放入 Xcode 中,查看它是否可以编译,然后对其进行调试。如果您无法使其正常工作,请尽可能将代码发回,我们将帮助您摆脱困境,但我不会在论坛上校对一堆代码

标签: ios json swift nsarray


【解决方案1】:

不是答案,但这可能会对您有所帮助,您可能应该在编写如下内容时检查您的属性是否为零:curr_message.id = onemessage["chatId"] as! String。 你可以做什么:

if let chatId = onemessage["chatId"] as? String {
   curr_message.id = chatId
}

或者,如果你想让它更简单,你可以使用Swifty JSON 并编写如下内容:

curr_message.id = onemessage["chatId"].stringValue

希望对你有帮助!

【讨论】:

  • 请注意:SwiftyJSON 的 onemessage["chatId"].stringValue 与 Swift 的 onemessage["chatId"] as! String 相同。如果您希望使用 SwiftyJSON 确保 Optionals 的安全性,您仍然必须使用 if let,但使用 onemessage["chatId"].string 而不是 Swift 的 onemessage["chatId"] as? String
  • @EricD 我调试了代码并应用了你们提出的 if let 建议,一切正常,直到 if 语句失败的行 if let dataArray = anItem["message"] as? NSArray {,程序直接跳转到 curr_chat.chat_messages = chat_messages ,我不知道为什么会这样
  • 您是否尝试将其转换为 NSDictionary ?
【解决方案2】:

我真的不知道这是否真的会帮助某人,但我已经被这个阻止了 3 天。我终于看到了这个问题,从字面上看,这个问题就是我的答案,感谢@Alk。简而言之,我正在处理这种类型的数据(NSArray):

[<__NSArrayM 0x6000000556e0>(
{
    author = Julioenred;
    id = 1;
    text = "hello world";
},
{
    author = Pepe;
    text = "Saludos!!";
}
)
]

我需要的数据是每个索引的作者和文本,所以我能够做到这一点:

for i in data.first as! [Dictionary<String, AnyObject>] {
    let message = Message(message: "", user: "")
    if let author = i["author"] as? String {
       message.author = author
    }
    if let text = i["text"] as? String {
       message.text = text
    }
 }

基本上我在字典中搜索我正在寻找的键,如果有人问,这是对象消息:

import Foundation

class Message: Mappable {
    var author: String? = ""
    var text: String? = ""
    
    init(message: String, user: String) {
        self.author = user
        self.text = message
    }
}

【讨论】: