我的 JSON 响应的某些属性没有加载到我的模型中

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

我在访问我的 JSON 响应

的几个属性时收到以下错误

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

在下面的 JSON 响应中,我遇到了关于 author、urlToimage 和 Content 等的错误。我无法找出原因。

"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]"

我正在使用以下结构模型。

struct Article: Decodable {

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

请帮我解决这个问题。

请仔细阅读错误信息。

明确表示在第16项(JSONKey(stringValue: "Index 15", intValue: 15))数组articles(CodingKeys(stringValue: "articles")没有值(valueNotFound / Expected String value but found null instead ) 对于键 urlToImage (CodingKeys(stringValue: "urlToImage")

在结构中声明 urlToImage 为可选

let urlToImage: String?

旁注:

您可以通过添加 iso8601 日期解码将 urlurlToImage 声明为 URL 而无需任何更改,将 publishedAt 声明为 Date策略。