【发布时间】:2020-11-16 05:14:11
【问题描述】:
我正在尝试解析 JSON,但不断收到不正确的格式错误。我从 FoodData Central(美国农业部的营养 API)返回的 JSON 如下:
{
dataType = "Survey (FNDDS)";
description = "Chicken thigh, NS as to cooking method, skin not eaten";
fdcId = 782172;
foodNutrients = (
{
amount = "24.09";
id = 9141826;
nutrient = {
id = 1003;
name = Protein;
number = 203;
rank = 600;
unitName = g;
};
type = FoodNutrient;
},
{
amount = "10.74";
id = "9141827";
nutrient = {
id = 1004;
name = "Total lipid (fat)";
number = 204;
rank = 800;
unitName = g;
};
type = FoodNutrient;
}
);
}
我的结构:
struct Root: Decodable {
let description: String
let foodNutrients: FoodNutrients
}
struct FoodNutrients: Decodable {
// What should go here???
}
从 JSON 来看,foodNutrients 看起来是一个未命名对象的数组,每个对象的值都有 amount: String、id: String 和 nutrient: Nutrient(有 id、name 等...)但是,忘记了Nutrient 对象,我什至无法解析数量。
struct FoodNutrients: Decodable {
let amounts: [String]
}
我不认为它是一个字符串数组,但我不知道 foodNutrients 中的 () 表示什么。
我将如何解析这个 JSON。我正在使用 Swift 5 和 JSONDecoder。为了得到 JSON,我使用 JSONSerializer,然后打印出上面的 JSON。
【问题讨论】:
-
它不是格式良好的 json。我检查了一个 json 格式化程序和验证程序。无效 (RFC 8259)
-
我也检查过,这很奇怪,因为它来自美国农业部的 API。我所做的就是使用 JSONSerialization 将数据转换为 JSON,然后打印它
标签: json swift parsing swift5 jsondecoder