Swift 5 解析奇怪的json格式

Swift 5 Parsing strange json format

我正在尝试解析 JSON,但不断收到格式不正确的错误。 JSON 我从 FoodData Central(美国农业部的营养 API)得到的结果如下:

{
    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 和 JSON 解码器。为了获得 JSON 我使用 JSONSerializer,然后打印出上面的 JSON。

foodNutrients 中的 () 表示它包含一个对象数组 - 在这种情况下是 FoodNutrient 对象。因此,您的根对象应如下所示:

struct Root: Decodable {
    let description: String
    let foodNutrients: [FoodNutrient]
}

现在 foodNutrient 除了 nutrient 对象之外直接了当:

struct FoodNutrient: Decodable {
    let id: Int // <-- in your example it is an integer and in the second object a string, choose the fitting one from the API
    let amount: String
    let nutrient: Nutrient
}

营养对象应该是这样的:

struct Nutrient: Decodable {
    let name: String
    let number: Int
    let rank: Int
    let unitName: String 
}

使用Decodable 是序列化JSON 的一种好而简单的方法。希望有所帮助。编码愉快:)

这是不是一个JSON。这是 openStep 格式的 属性 列表。

这是它的建模方式(使用 String 而不是 Int):

struct Root: Decodable {
    let description: String
    let foodNutrients: [FoodNutrient]
}

struct FoodNutrient: Decodable {
    let id: String
    let amount: String
    let nutrient: Nutrient
}

struct Nutrient: Decodable {
    let name: String
    let number: String
    let rank: String
    let unitName: String
}

然后像这样解码:

try PropertyListDecoder().decode(Root.self, from: yourStr)