我正在建立一个Tableview中使用的Food类,其中包含来自Food Database API的数据提要。

该课程的正确结构是什么?如果营养价值(例如卡路里)不随测量而变化,那么这当然是微不足道的,但是每一种营养都取决于它。

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()

}


目前,这只是从每种营养中提取每种营养的价值。任何人都可以就如何构建应用程序提供指导,然后我就可以提供数据了。

最佳答案

我不太确定您的问题到底是什么,但是我将如何解析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)

09-11 17:54
查看更多