将字典数组转换成字典并初始化模型

时间:2019-01-18 08:10:59

标签: ios arrays swift dictionary alamofire

我从服务器获取了一系列词典。然后我试图将其转换为jsonDictionary,似乎我做错了什么。我如何也可以初始化我的用户模型? 这是代码:

func getSearchedUsers(key: String, completion: @escaping(SearchedUsers?) -> Void) {
    if let url = URL(string: baseURL + "search?qerty=\(key)") {
        Alamofire.request(url).responseJSON { (response) in
            if let array = response.result.value as? [[String:Any]] {
                var dictionary = [String:Any]()
                for item in array {
                    for (key, value) in item {
                        dictionary.updateValue(value, forKey: key)
                    }
                }
            } else {
                completion(nil)
            }
        }
    }
}

这是模型:

class SearchedUsers {
    let id: Int
    let username: String?
    let fullName: String?
    let profilePicture: URL?
    let isPrivate: Bool

    init(data: [String: Any]) {
        id = data["id"] as! Int
        username = data["username"] as? String
        fullName = data["fullName"] as? String
        isPrivate = data["isPrivate"] as! Bool
        profilePicture = data["profilePicUrl"] as? URL
    }
}

我该如何使用它?

这是我得到的答复:

[Result]: SUCCESS: (
    {
    byline = "21.9k followers";
    followerCount = 21911;
    friendshipStatus =         {
        following = 0;
        "incoming_request" = 0;
        "is_bestie" = 0;
        "is_private" = 0;
        "outgoing_request" = 0;
    };
    fullName = "Undefined Variable";
    hasAnonymousProfilePicture = 0;
    id = 8513861541;
    isPrivate = 0;
    isVerified = 0;
    mutualFollowersCount = 0;
    picture = "https://scontent-ams3-1.cdninstagram.com/vp/885ac17fe17809de22790f0559f61877/5CD13A1C/t51.2885-19/s150x150/39312159_480582069091253_3011569611268161536_n.jpg?_nc_ht=scontent-ams3-1.cdninstagram.com";
    pk = 8513861541;
    profilePicId = "1857507164564653723_8513861541";
    profilePicUrl = "https://scontent-ams3-1.cdninstagram.com/vp/885ac17fe17809de22790f0559f61877/5CD13A1C/t51.2885-19/s150x150/39312159_480582069091253_3011569611268161536_n.jpg?_nc_ht=scontent-ams3-1.cdninstagram.com";
    reelAutoArchive = on;
    username = "i_am_variable";
},
    {
    byline = "467 followers";
    followerCount = 467;
    friendshipStatus =         {
        following = 0;
        "incoming_request" = 0;
        "is_bestie" = 0;
        "is_private" = 0;
        "outgoing_request" = 0;
    };
    fullName = undefined;
    hasAnonymousProfilePicture = 0;
    id = 8657882817;
    isPrivate = 0;
    isVerified = 0;
    latestReelMedia = 1547794887;
    mutualFollowersCount = 0;
    picture = "https://scontent-ams3-1.cdninstagram.com/vp/fb3c992c899aa269bdce2c4c1db8575b/5CD068BA/t51.2885-19/s150x150/46378106_2062632390480778_1266491662662631424_n.jpg?_nc_ht=scontent-ams3-1.cdninstagram.com";
    pk = 8657882817;
    profilePicId = "1931972067016763185_8657882817";
    profilePicUrl = "https://scontent-ams3-1.cdninstagram.com/vp/fb3c992c899aa269bdce2c4c1db8575b/5CD068BA/t51.2885-19/s150x150/46378106_2062632390480778_1266491662662631424_n.jpg?_nc_ht=scontent-ams3-1.cdninstagram.com";
    reelAutoArchive = on;
    username = "undefi.ned";
})

这是一个字典数组,我需要以适当的方式对其进行解析。那是我的主要问题。

2 个答案:

答案 0 :(得分:0)

如果您知道如何解析字典,那么您应该知道如何制作字典;)有一些工具可以制作您自己的模型类,例如:http://www.jsoncafe.com/

编辑:如罗伯特在下面的评论部分中所建议,您可以学习Decodable

您可以使用它来使自己了解模型类的外观或外观。随便使用它。在一个体面的项目中,可能会有大量数据,并且您不想用它来创建类模型,特别是如果您是唯一处理iOS项目的人。

因此,我们假设,根据您的帖子,我们拥有以下json数据:

{
    "id": 1,
    "username": "dd",
    "fullName": "dd",
    "profilePicture": "ddd",
    "isPrivate": true
}

我们可以像这样建立一个模型:

//
//  UserRootClass.swift
//  Model Generated using http://www.jsoncafe.com/
//  Created on January 18, 2019

import Foundation

class UserRootClass : NSObject {

    var fullName : String!
    var id : Int!
    var isPrivate : Bool!
    var profilePicture : String!
    var username : String!


    /**
     * Instantiate the instance using the passed dictionary values to set the properties values
     */
    init(fromDictionary dictionary: [String:Any]){
        fullName = dictionary["fullName"] as? String
        id = dictionary["id"] as? Int
        isPrivate = dictionary["isPrivate"] as? Bool
        profilePicture = dictionary["profilePicture"] as? String
        username = dictionary["username"] as? String
    }

    /**
     * Returns all the available property values in the form of [String:Any] object where the key is the approperiate json key and the value is the value of the corresponding property
     */
    func toDictionary() -> [String:Any]
    {
        var dictionary = [String:Any]()
        if fullName != nil{
            dictionary["fullName"] = fullName
        }
        if id != nil{
            dictionary["id"] = id
        }
        if isPrivate != nil{
            dictionary["isPrivate"] = isPrivate
        }
        if profilePicture != nil{
            dictionary["profilePicture"] = profilePicture
        }
        if username != nil{
            dictionary["username"] = username
        }
        return dictionary
    }

}

上面的模型类是使用我上面提供的工具制作的,但是我删除了NSCoding协议方法。

我希望这会有所帮助!祝您好运,欢迎您使用Stackoverflow。

答案 1 :(得分:0)

如果您拥有Struct而不是Class,则可以使用Decodable进行轻松解析。这是Alamofire 5.0中的示例

struct SearchedUsers: Decodable {
    let id: Int
    let username: String?
    let fullName: String?
    let profilePicture: URL?
    let isPrivate: Bool
}

AF.request("http://url_endpoint/").responseData { response in
            do {
                // data we are getting from network request
                let decoder = JSONDecoder()
                let response = try decoder.decode([SearchedUsers].self, from: response.data!)

            } catch { print(error) }
        }