json - 使用 json 数据的 Food 类的正确结构

标签 json swift data-structures

我正在构建一个在表格 View 中使用的食品类,其中包含来自食品数据库 API 的数据源。

这个类的正确结构是什么?如果营养值(value)(例如卡路里)不随测量而改变,那么这当然是微不足道的,但它会改变,因此每种营养素都依赖于它。

json 看起来像这样 ( https://api.nal.usda.gov/ndb/reports/?ndbno=01009&type=f&format=json&api_key=DEMO_KEY ):

"report": {
    ...
    "food": {
        ...
        "name": "Cheese, cheddar",
        ...
        "nutrients": [
            {
                ...
                "unit": "kcal",
                ...
                "measures": [
                    {
                        "label": "cup, diced",
                        "eqv": 132.0,
                        "eunit": "g",
                        "qty": 1.0,
                        "value": "48.87"
                    },
                    {
                        "label": "cup, melted",
                        "eqv": 244.0,
                        "eunit": "g",
                        "qty": 1.0,
                        "value": "90.33"
                    },

我最初的想法是先访问数据,然后再构建类。这就是我所做的:

static func getFood (withSearchString search: String, completion: @escaping ([Double]) -> ()) {

    let url = "https://api.nal.usda.gov/ndb/reports/?ndbno=01009&type=f&format=json&api_key=\(key)"
    let request = URLRequest(url: URL(string: url)!)

    let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in

        var value: [Double] = []

        if let data = data {
            do {
                if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
                    if let report = json["report"] as? [String: Any] {
                        if let food = report["food"] as? [String: Any] {
                            if let nutrients = food["nutrients"] as? [[String: Any]] {

                                for dataPoint in nutrients {

                                    if let measures = dataPoint["measures"] as? [[String: Any]]{

                                        for dataPoint2 in measures {
                                            if let value2 = dataPoint2["value"] as? Double {
                                                value.append(value2)
                                            }
                                        }

                                    }

                                }
                            }

                        }
                    }
                }
            }catch {
                print(error.localizedDescription)
            }
            // pass the instance as an argument to the completion block accessed in the nutrition class
            completion(value)
        }
    }
    task.resume()

}

目前,这只是提取每种营养成分的每个指标的值(value)。任何人都可以指导如何构建应用程序,然后我可以提供数据。

最佳答案

我不太确定你的问题到底是什么,但我会做解析 JSON 来创建不同的模型,如下所示:

struct Measure: Codable {
    let label: String
    let eqv: Double
    let unit: String
    let qty: Int
    let value: String
}

struct Nutrient: Codable {
    let unit: String
    let measures: [Measure]
}

struct Food: Codable {
    let name: String
    let nutrients: [Nutrient]
}

然后你可以像这样使用 JSONDecoder 将 JSON 解码为这些模型

try JSONDecoder().decode(Food.self, from: data)

关于json - 使用 json 数据的 Food 类的正确结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47554316/

相关文章:

java - 如何实现连通房间?

C# Object 将Attributes的值做成json对象

ios - 我如何在我的应用程序中通过播放器播放 UNNotificationSound.default()?

swift : Animate SKSpriteNode Gradient

ios - 更改 UITableViewCell 上 accessoryView 的大小

data-structures - 了解融合树?

php - 最后一个值没有出现在动态 php 数组中

java - 将 JSONObject 解析为自定义类

java - 需要自定义Gson反序列化,只需要单元素JSON,转为Object

c++ - 如何实现经纬度值的邻近搜索?