问题描述
我正在尝试从 CalorieNinja API 解码 JSON 格式,但似乎他们的 json 中的等号正在抛弃我的代码。这是我解码 JSON 文件的代码:
let dataTask = session.dataTask(with: request) { (data,response,error) in
//check errors
if error == nil && data != nil {
let decoder = JSONDecoder()
do{
let result = try decoder.decode(Result.self,from: data!)
print(result)
}catch{
print("there was an error")
print(error)
}
}
}
这是我的结构:
struct FoodItem: Codable {
var name: String?
var calories: String?
}
struct Result: Codable {
var items: [FoodItem]?
}
这是从 CalorieNinjas 返回的 JSON 格式(这只是一个示例,不是我的代码的输出):
{
items = (
{
calories = "18.2";
"carbohydrates_total_g" = "3.9";
"cholesterol_mg" = 0;
"fat_saturated_g" = 0;
"fat_total_g" = "0.2";
"fiber_g" = "1.2";
name = tomato;
"potassium_mg" = 23;
"protein_g" = "0.9";
"serving_size_g" = 100;
"sodium_mg" = 4;
"sugar_g" = "2.6";
}
);
}
最后这里是错误,如果它有帮助的话:
typeMismatch(Swift.String,Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "items",intValue: nil),_JSONKey(stringValue: "Index 0",intValue: 0),CodingKeys(stringValue: "calories",intValue: nil)],debugDescription: "Expected to decode String but found a number instead.",underlyingError: nil))