Search code examples
iosswiftdecodable

How do I properly decode this json string using decodable?


I have the following json string:

{"weight":[{"bmi":24.75,"date":"2020-01-20","logId":1000,"source":"API","time":"23:59:59","weight":200}]}

I want to convert it to a Swift object in order to access the different values. Here is what I am trying to do, I have these structs setup:

struct FitbitResponseModel: Decodable  {
    let weight: [FitbitResponseData]
}


struct FitbitResponseData: Decodable  {
    let bmi: Int
    let date: String
    let logId: Int
    let source: String
    let time: String
    let weight: Int
}

And then I have this method to decode the json string:

func parseJSON(data: Data) -> FitbitResponseModel? {

    var returnValue: FitbitResponseModel?
    do {
        returnValue = try JSONDecoder().decode(FitbitResponseModel.self, from: data)
    } catch {
        print("Error took place: \(error.localizedDescription).")
    }

    return returnValue
}

However when I try to run it I get the error that the data couldn’t be read because it isn’t in the correct format. What am I doing wrong? Any help is appreciated.

Thanks in advance!


Solution

  • change

    let bmi: Int 
    

    to

    let bmi: Double 
    

    beacuse it's value is coming out to be 24.75 in your response if any variable type doesn't match to JSON response whole model wouldn't map in Codable protocol (Encodable and Decodable)