如何手动将 JSON 文件中的嵌套数组解析为数据模型的嵌套数组?

问题描述 投票:0回答:1

我最近开始学习 Swift,并面临下一个问题。我需要使用 Alamofire 框架并实现从 JSON 文件到数据模型的手动数据解析。在本例中,JSON 文件有一个嵌套数组。我写了代码,但出现错误消息。

需要做什么来执行这样的解析?

这是 JSON 文件。

["type": product, "number": 10, "offset": 0, "processingTimeMs": 4735, "products": <__NSArrayI 0x600002629e00>(
{
    id = 10026738;
    image = "https://spoonacular.com/productImages/10026738-312x231.jpg";
    imageType = jpg;
    title = "Jenos by totinos crsp n tsty pizza for 1 combo";
},
{
    id = 8215206;
    image = "https://spoonacular.com/productImages/8215206-312x231.jpg";
    imageType = jpg;
    title = "Supreme sausage, pepperoni, green, red and yellow peppers, roasted garlic & red onions brick oven crust pizza, supreme";
},
{
    id = 9822788;
    image = "https://spoonacular.com/productImages/9822788-312x231.jpg";
    imageType = jpg;
    title = "Grisinetos pizza";
},
...

)
, "totalProducts": 16410]

这是数据模型。

struct Product: Decodable {
    let id: Int
    let title: String
    let imageType: String
}

struct Grocery: Decodable {
    let products: [Product]
    let totalProducts: Int
    let type: String
    let offset: Int
    let number: Int
}

这是我写的函数

private func fetchProducts() {
    AF.request(groceryLink)
        .validate()
        .responseJSON { dataResponse in
        switch dataResponse.result {
        case .success(let value):
            guard let groceryDetails = value as? [String: Any] else { return }
            
            var products: [Product] = []
            
            for productDetails in groceryDetails["products"] {
                let product = Product(
                    id: productDetails["id"] as? Int ?? 0,
                    title: productDetails["title"] as? String ?? "",
                    imageType: productDetails["imageType"] as? String ?? ""
                )
                products.append(product)
            }

            let grocery = Grocery(products: products,
                                  totalProducts: groceryDetails["totalProducts"] as? Int ?? 0,
                                  type: groceryDetails["type"] as? String ?? "",
                                  offset: groceryDetails["offset"] as? Int ?? 0,
                                  number: groceryDetails["number"] as? Int ?? 0)
            
        case .failure(let error):
            print(error)
        }
    }
}
arrays json swift parsing alamofire
1个回答
0
投票

我找到了这个任务的解决方案。

在循环的第一行,需要将接收到的数据转换为字典数组 [[String: Any]]

固定代码在这里:

private func fetchProducts() {
    AF.request(groceryLink)
        .validate()
        .responseJSON { dataResponse in
        switch dataResponse.result {
        case .success(let value):
            guard let groceryDetails = value as? [String: Any] else { return }
            
            var products: [Product] = []
            
            for productDetails in groceryDetails["products"] as? [[String: Any]] ?? [] {
                let product = Product(
                    id: productDetails["id"] as? Int ?? 0,
                    title: productDetails["title"] as? String ?? "",
                    imageType: productDetails["imageType"] as? String ?? ""
                )
                products.append(product)
            }

            let grocery = Grocery(products: products,
                                  totalProducts: groceryDetails["totalProducts"] as? Int ?? 0,
                                  type: groceryDetails["type"] as? String ?? "",
                                  offset: groceryDetails["offset"] as? Int ?? 0,
                                  number: groceryDetails["number"] as? Int ?? 0)
            
        case .failure(let error):
            print(error)
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.