Search code examples
jsonswiftxcodejsondecoder

Having trouble decoding JSON file in swift


I am trying to decode a JSON format from CalorieNinja API but it appears that the equals signs in their jsons are throwing my code off. Here is my code for decoding the JSON file:

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

Here are my structs:


struct FoodItem: Codable {
    var name: String?
    var calories: String?
}

struct Result: Codable {
    
    var items: [FoodItem]?
    
}

Here is the JSON format that gets returned from CalorieNinjas(this is just an example this is not the output of my code):

{
    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";
        }
    );
}

And lastly here is the error if it helps at all:

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

Solution

  • You can check CalorieNinja API again.
    I think the calories field should be Double? due to their document.enter image description here