Search code examples
iosfoundationdecodable

Some properties of my JSON response are not loading into my model


I am getting the following error while accessing few properties my JSON response

valueNotFound(Swift.String, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "articles", intValue: nil), _JSONKey(stringValue: "Index 15", intValue: 15), CodingKeys(stringValue: "urlToImage", intValue: nil)], debugDescription: "Expected String value but found null instead.", underlyingError: nil))

In the following JSON response, I am getting above error for author, urlToimage & Content etc. I am not able to find out the reason for it.

"author": "PTI",
"title": "Rape Survivor, Set Ablaze in UP's Unnao a Day Ago, Critical; Doctors Say Her Vitals Are 'Very Low' - News18",
"description": "The Delhi Traffic Police on Thursday provided a 'green corridor' for hindrance-free movement of the ambulance carrying her from the airport to the hospital.",
"url": "https://www.news18.com/news/india/rape-survivor-set-ablaze-in-ups-unnao-a-day-ago-on-ventilator-at-delhi-hosp-docs-say-shes-critical-2414083.html",
"urlToImage": "https://images.news18.com/ibnlive/uploads/2019/12/Safdarjung-hospital-Unnao-rape.jpg",
"publishedAt": "2019-12-06T05:58:00Z",
"content": "New Delhi: The rape survivor from Unnao, who was airlifted to Delhi and admitted to the Safdarjung Hospital here, is extremely critical and on ventilator, doctors attending to her said on Friday.
"The condition of the patient is extremely critical and she is… [+1187 chars]"

I am using the following struct model.

struct Article: Decodable {

    let author: String
    let title: String
    let description: String
    let urlToImage: String
    let publishedAt: String
    let content: String
}

Please help me with this.


Solution

  • Please read the error message carefully.

    It clearly states that in the 16th item (JSONKey(stringValue: "Index 15", intValue: 15)) in the array articles (CodingKeys(stringValue: "articles") there is no value (valueNotFound / Expected String value but found null instead) for key urlToImage (CodingKeys(stringValue: "urlToImage")

    Declare urlToImage in the struct as optional

    let urlToImage: String?
    

    Side note:

    You can declare url and urlToImage as URL without any changes and publishedAt as Date by adding the iso8601 date decoding strategy.