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

时间:2017-11-29 13:46:05

标签: json swift data-structures

我正在使用食物数据库API中的数据源构建tableview中使用的Food类。

这门课的正确结构是什么?如果营养价值(例如卡路里)没有随着测量而改变,那么这当然是微不足道的,但确实如此,每种营养素都依赖于它。

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

}

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

1 个答案:

答案 0 :(得分:0)

我不确定你的问题究竟是什么,但是我要解析JSON的方法是创建不同的模型:

import sys
sys.path.append("..")
from .. import file1

然后你可以使用像这样的JSONDecoder将你的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]
}