简体   繁体   English

无法使用 Alamofire 解析 json

[英]Unable to parse json with Alamofire

I have used Alamofire before but had no problems, looks like this time my json is a little bit weird, I can not find a way to pass it.我以前用过Alamofire,但没有问题,看来这次我的json有点奇怪,我找不到通过它的方法。
This is how my json looks like, I have simplified it but context is the same:这就是我的 json 的样子,我已经简化了它,但上下文是一样的:

    {
        "categories": [
            {
                "categories": {
                    "id": 1,
                    "name": "A"
                }
            },
            {
                "categories": {
                    "id": 2,
                    "name": "B"
                }
            },
            {
                "categories": {
                    "id": 3,
                    "name": "C"
                }
            }]
}

Also, I have a Category structure like this:另外,我有一个这样的Category结构:

struct Category {
    let id: Int
    let name: String
    
    init(id: Int, name: String) {
        self.id = id
        self.name = name
    }
}

And finally, my Alamofire request :最后,我的Alamofire request

func getCategories(completed: @escaping () -> ()) {
        let baseUrl = ""
        
        let api_key = ""
        
        let headers : HTTPHeaders = [
            "user-key":api_key
        ]
        
        Alamofire.request(baseUrl, method: .get, parameters: nil, headers: headers).responseJSON { response in
            
            guard let value = response.value as? [String:Any] else { return }
            guard let cats = value["categories"] as? [Category] else { return}
            print(cats)
            
            completed()
        }
    }

Problem - I have printed a value and it works fine, but this print(cats) never gets called because of the line before, it returns. Problem - 我已经打印了一个值并且它工作正常,但是这个print(cats)永远不会因为之前的行而被调用,它会返回。
Looks like I have a problem with models and parsing, cannot figure out why.看起来我的模型和解析有问题,不知道为什么。

Alamofire's responseJSON(completionHandler:) uses the jsonObject(with:opt:) function of the native JSONSerialization . Alamofire 的responseJSON(completionHandler:)使用原生 JSONSerialization 的jsonObject(with:opt:) function What this does is to convert the json data to Swift native types.这样做是将 json 数据转换为 Swift 本机类型。 Whenever there is a json object like this:每当有这样的 json object 时:

{
    "id": 3,
    "name": "C"
}

will be translated to a Dictionary [String: Any] .将被翻译成字典[String: Any] Whenever there is a json array of json objects like this:每当有这样的 json 对象的 json 数组时:

[
    {
        "id": 1,
        "name": "A"
    }
]

will be translated to an array of Dictionaries [[String: Any]] .将被翻译成字典数组[[String: Any]] So, your getCategories(completed:) function should, most likely, be like this:因此,您的getCategories(completed:) function 很可能应该是这样的:

func getCategories(completed: @escaping () -> ()) {
    let baseUrl = ""
    
    let api_key = ""
    
    let headers: HTTPHeaders = [
        "user-key":api_key
    ]
    
    Alamofire.request(baseUrl, method: .get, parameters: nil, headers: headers).responseJSON { response in
        var categories = [Category]()
        if let json = response.value as? [String: Any] {
            if let array = json["categories"] as? [[String: Any]] {
                for category in array {
                    let categoryDetails = category["categories"] as? [String: Any]
                    if let id = categoryDetails?["id"] as? Int, let name = categoryDetails?["name"] as? String {
                        categories.append(Category(id: id, name: name))
                    }
                }
            }
        }
        print(categories)
        
        completed()
    }
}

This has a lot of boilerplate code.这有很多样板代码。 You should consider using the native Codable type and JSONDecoder instead.您应该考虑改用本机Codable类型和JSONDecoder It needs less code.它需要更少的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM