【问题标题】:Convert array of dictionaries into a dictionary and init the model将字典数组转换为字典并初始化模型
【发布时间】:2019-06-12 11:28:28
【问题描述】:

我正在从服务器获取一系列字典。然后我试图将它转换为 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";
})

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

【问题讨论】:

  • 输出/结果是什么?有任何错误信息吗?
  • 如果您添加 json 的示例代码会很好。无论如何,您使用的是 Swift 4+ 吗?然后你可以尝试搜索一下Codable
  • 这是一篇关于 JSON 解析的精彩博文 - 也许您想从基础开始:medium.com/@nimjea/json-parsing-in-swift-2498099b78f。它使用 iOS 提供的开箱即用的 JSON 编码/解码工具。恕我直言,没有必要为此使用外部库。
  • @EmmaVagradyan,如果您在帖子中发布您的一些响应数据,那么其他人可以很容易地帮助您。
  • @Kuldeep,请查看我更新的问题

标签: ios arrays swift dictionary alamofire


【解决方案1】:

如果你有 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) }
        }

【讨论】:

    【解决方案2】:

    如果您知道如何解析字典,那么您应该知道如何制作一个;)有一些工具可以制作您自己的模型类,例如: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。

    【讨论】:

    • 如果你认为 json 看起来像这样,你也可以认为她使用的是最新版本的 Swift,所以你应该建议 struct 符合Decodable
    • 对。感谢您的建议。
    • 我知道如何从字典中初始化,但我的问题是我得到了一个字典数组,而不是字典,而且我不知道如何以正确的方式转换成字典。我已经在问题中发布了我这样做的方式,但它不能按需要工作。我得到的回复有以下类型[{"key":"value"}]
    • 是的,我使用 Swift 4.2,感谢@RobertDresler 的建议
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-21
    • 2016-05-15
    • 2018-10-12
    • 2017-10-23
    • 2020-09-16
    • 2021-08-10
    • 1970-01-01
    相关资源
    最近更新 更多