访问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:“期望的字符串值,但发现为null。”,底层错误:nil))


在下面的JSON响应中,我遇到了作者,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
}


请帮我解决一下这个。

最佳答案

请仔细阅读错误消息。

它明确指出在数组JSONKey(stringValue: "Index 15", intValue: 15)articles)中的第16个项目(CodingKeys(stringValue: "articles")中,键valueNotFound / Expected String value but found null insteadurlToImage)没有值(CodingKeys(stringValue: "urlToImage"

在结构中声明urlToImage为可选

let urlToImage: String?


边注:

通过添加url日期解码策略,可以将urlToImageURL声明为publishedAt且将Date声明为iso8601

关于ios - 我的JSON响应的某些属性未加载到我的模型中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59211650/

10-11 12:09