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/

相关文章:

javascript - 使用 javascript 更改 JSON 结构

ios - 针对特定设备的缩放

data-structures - Redis - 排序字典

mysql - 可能由于表结构而无法插入数组

java - Google App Engine 端点中的自定义 JSON 实体解析

java - 什么是 JSON REST 接口(interface)

javascript - NVD3 - 将 JSON url 数据与 LinePlusBarChart 结合使用(映射值)

ios - 如何在 didReceiveRemoteNotification 中获取 userInfo JSON 值

ios - 为什么 DispatchQueue.main.async 会对单元自动调整大小产生影响?

ocaml - 链表 OCaml