我的 JSON 响应的某些属性未加载到我的模型中
Posted
技术标签:
【中文标题】我的 JSON 响应的某些属性未加载到我的模型中【英文标题】:Some properties of my JSON response are not loading into my model 【发布时间】:2019-12-06 10:47:41 【问题描述】:我在访问我的 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: "预期的字符串值,但发现为空。", 底层错误: nil))
在以下 JSON 响应中,作者、urlToimage 和内容等出现上述错误。我无法找出原因。
"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
请帮我解决这个问题。
【问题讨论】:
您需要向我们展示您是如何解析 JSON 的。 【参考方案1】:请仔细阅读错误信息。
它明确指出,在数组articles
(CodingKeys(stringValue: "articles"
) 中的第 16 项 (JSONKey(stringValue: "Index 15", intValue: 15)
) ) 密钥 urlToImage
(CodingKeys(stringValue: "urlToImage"
) 没有价值 (valueNotFound / Expected String value but found null instead
) >)
将结构中的urlToImage
声明为可选
let urlToImage: String?
旁注:
您可以通过添加iso8601
日期解码策略将url
和urlToImage
声明为URL
而不做任何更改,并将publishedAt
声明为Date
。
【讨论】:
以上是关于我的 JSON 响应的某些属性未加载到我的模型中的主要内容,如果未能解决你的问题,请参考以下文章