Search code examples
swiftnsmutablearray

Swift code problem - trying to cast objects out from a NSMutableArray as a custom object


Here is my code and it fails to execute as noted below.

I am trying to cast an object to my custom data type called UserData. First problem I have is don't understand how to get the value out of the array correctly Second I cannot seem to cast the object as the type I need, UserData. What I am doing wrong?

    func parseJSON(_ data:Data) {

        var jsonResult = NSArray()
        var users = NSMutableArray();

        do{
            jsonResult = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSArray
        } catch let error as NSError {
            print(error)
        }

        var jsonElement = NSDictionary()
        for i in 0 ..< jsonResult.count {

            print("loop count :", i );

            jsonElement = jsonResult[i] as! NSDictionary

            let user = UserData()

            //the following insures none of the JsonElement values are nil through optional binding
            if let UserID = jsonElement["Userid"] as? String,
                let firstName = jsonElement["First_Name"] as? String,
                let lastName = jsonElement["Last_Name"] as? String,
                let userSessionID = jsonElement["Session_ID"] as? String
            {

                user.UserID = UserID
                user.FirstName = firstName
                user.LastName = lastName
                user.UserSessionID = userSessionID

                print("users firstName:", user.FirstName ?? "blank");

            }

            users.add(user)
        }

        print("users size:", users.count); // this shows 2 
        // So i know I have data loaded... BUT when i try and 
        // get it then it all goes to heck. See below


        // NOT SURE what I am doing here...
        // Thought it was java like where I could just get a
        // item from the NSMutableArray using an index value
        // then cast it as my UserData object
        // and print the output... but this does not work 
        // Why is this so hard?? 

        let userDataVal = users.index(of: 0) as! UserData;
        print("firstName:", userDataVal.FirstName);

    }

Solution

  • Better approach would be to use JSONDecoder() instead of a JSONSerailizer. Try using the following code.

    struct User: Codable {
        var userId, firstName, lastName, userSessionId: String
    
        enum CodingKeys: String, CodingKey {
            case userId = "Userid"
            case firstName = "First_Name"
            case lastName = "Last_Name"
            case userSessionId = "Session_ID"
        }
    }
    
    func parseJSON(_ data: Data) {
        do {
            let users = try JSONDecoder().decode([User].self, from: data)
            users.forEach { user in
                print("users first name:", user.firstName)
            }
        } catch {
            print(error.localizedDescription)
        }
    }