我正在我的Swift App中解码JSON响应,并且该代码一直工作到决定停止工作为止。
这是我的json存储库
{"foods":[{"food_name":"Milk Chocolate","brand_name":"Snickers","serving_weight_grams":41.7,"nf_calories":212.3,"nf_total_fat":11.6,"nf_saturated_fat":4,"nf_total_carbohydrate":22.7,"nf_protein":3.9}]}
这是解码我的json的代码
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let data = data else { return }
print(String(data: data, encoding: .utf8)!)
do {
//Decode dataResponse received from a network request
let decoder = JSONDecoder()
let foods = try decoder.decode(JSONFoods.self, from: data) //Decode JSON Response Data
self.jsonfood = foods.JSONFood[0]
print(self.jsonfood!)
} catch let parsingError {
print("Error", parsingError)
}
}
task.resume()
我的结构是
struct JSONFoods: Decodable {
var JSONFood: [JSONFood]
}
struct JSONFood: Decodable{
var food_name: String
var brand_name: String
var nf_calories: Int
var nf_protein: Int
var nf_total_fat: Int
var nf_total_carbohydrate: Int
var serving_weight_grams: Int
}
我收到的错误消息是这个
keyNotFound(CodingKeys(stringValue:“ JSONFood”,intValue:nil),Swift.DecodingError.Context(codingPath:[],debugDescription:“没有与键CodingKeys(stringValue:\” JSONFood \“,intValue:nil相关联的值) )(\“ JSONFood \”)。“,underlyingError:nil))
如果我得到的是将解码( JSONFoods .self,来自:数据)替换为解码( JSONFood .self,来自:数据) 我收到此错误消息
keyNotFound(CodingKeys(stringValue:“ food_name”,intValue:nil),Swift.DecodingError.Context(codingPath:[],debugDescription:“没有与键CodingKeys相关联的值(stringValue:\” food_name \“,intValue:nil )(\“ food_name \”)。“,underlyingError:nil))
我到处搜索都没有运气,非常感谢
答案 0 :(得分:0)
您需要
struct Root: Codable {
let foods: [Food]
}
struct Food: Codable {
let foodName: String?
let brandName: String
let servingWeightGrams, nfCalories, nfTotalFat: Double
let nfSaturatedFat: Int
let nfTotalCarbohydrate, nfProtein: Double
enum CodingKeys: String, CodingKey {
case foodName = "food_name"
case brandName = "brand_name"
case servingWeightGrams = "serving_weight_grams"
case nfCalories = "nf_calories"
case nfTotalFat = "nf_total_fat"
case nfSaturatedFat = "nf_saturated_fat"
case nfTotalCarbohydrate = "nf_total_carbohydrate"
case nfProtein = "nf_protein"
}
}
首先:,您制作的JSONFood
应该是foods
第二个: food_name
在当前json根目录中不存在,因此将失败
let foods = try decoder.decode(JSONFoods.self, from: data) //Decode JSON Response Data
以防利用convertFromSnakeCase
let str = """
{"foods":[{"food_name":"Milk Chocolate","brand_name":"Snickers","serving_weight_grams":41.7,"nf_calories":212.3,"nf_total_fat":11.6,"nf_saturated_fat":4,"nf_total_carbohydrate":22.7,"nf_protein":3.9}]}
"""
do {
let res = JSONDecoder()
res.keyDecodingStrategy = .convertFromSnakeCase
let ss = try res.decode(Root.self, from:Data(str.utf8))
print(ss)
}
catch {
print(error)
}
struct Root: Codable {
let foods: [Food]
}
struct Food: Codable {
let foodName: String?
let brandName: String
let servingWeightGrams, nfCalories, nfTotalFat: Double
let nfSaturatedFat: Int
let nfTotalCarbohydrate, nfProtein: Double
}