JSON字符串中出现意外的nil

编程入门 行业动态 更新时间:2024-10-28 10:34:25
本文介绍了JSON字符串中出现意外的nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在应用程序中解析JSON,并且某些JSON具有我处理过的nil值.但是,该应用程序仍向我显示JSON包含nil值的错误.我的代码:

I parse JSON in my application and some of the JSONs have nil values which I handled. However, the app still shows me the error that JSON contains nil values. My code:

struct Response : Decodable { let articles: [Article] } struct Article: Decodable { let title: String let description : String let url : String let urlToImage : String } URLSession.shared.dataTask(with: url) { (data, response, error) in guard let data = data else { return } do { let article = try JSONDecoder().decode(Response.self , from : data) for i in 0...article.articles.count - 1 { if type(of: article.articles[i].title) == NSNull.self { beforeLoadNewsViewController.titleArray.append("") } else { beforeLoadNewsViewController.titleArray.append(article.articles[i].title) } if type(of : article.articles[i].urlToImage) == NSNull.self { beforeLoadNewsViewController.newsImages.append(newsListViewController.newsImages[newsListViewController.newsIndex]) } else { let url = URL(string: article.articles[i].urlToImage ?? "static.wixstatic/media/b77fe464cfc445da9003a5383a3e1acf.jpg") let data = try? Data(contentsOf: url!) if url != nil { //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch let img = UIImage(data: data!) beforeLoadNewsViewController.newsImages.append(img!) } else { beforeLoadNewsViewController.newsImages.append(newsListViewController.newsImages[newsListViewController.newsIndex]) }

这是运行应用程序的错误:

This is the error running the app:

FC91DEECC1631350EFA71C9C561D).description],debugDescription:预期的字符串值,但发现为空.",underlyingError:nil))

FC91DEECC1631350EFA71C9C561D).description], debugDescription: "Expected String value but found null instead.", underlyingError: nil))

注意:

此JSON可与其他没有nil值的网址一起使用.

Note:

This JSON works with other urls that don't have nil values.

这是json

{ "status": "ok", "source": "entertainment-weekly", "sortBy": "top", "articles": [ { "author": null, "title": "Hollywood's Original Gone Girl", "description": null, "url": "mariemcdonald.ew/", "urlToImage": null, "publishedAt": null }, { "author": "Samantha Highfill", "title": "‘Supernatural’: Jensen Ackles, Jared Padalecki say the boys aren’t going ‘full-mope’", "description": "", "url": "ew/tv/2017/10/18/supernatural-jensen-ackles-jared-padalecki-season-13/", "urlToImage": "ewedit.files.wordpress/2017/10/supernatural-season-13-episode-1.jpg?crop=0px%2C0px%2C2700px%2C1417.5px&resize=1200%2C630", "publishedAt": "2017-10-18T17:23:54Z" }, {

推荐答案

错误非常明显. JSONDecoder将NSNull映射到nil,因此如果解码器要将nil值解码为非可选类型,则解码器将引发错误.

The error is quite clear. JSONDecoder maps NSNull to nil so the decoder throws an error if it's going to decode a nil value to a non-optional type.

解决方案是将所有受影响的属性声明为可选.

The solution is to declare all affected properties as optional.

let title: String let description : String? let url : String let urlToImage : String?

或自定义解码器以将nil替换为空字符串.

or customize the decoder to replace nil with an empty string.

并且因为JSONDecoder将NSNull映射到nil,所以检查if ... == NSNull.self {是没有用的.

And because JSONDecoder maps NSNull to nil the check if ... == NSNull.self { is useless.

不要使用丑陋的C风格的基于索引的循环使用

Don't use ugly C-style index based loops use

let response = try JSONDecoder().decode(Response.self , from : data) for article in response.articles { beforeLoadNewsViewController.titleArray.append(article.title) }

PS:但是,为什么为了天堂的缘故,您将文章实例映射到(显然是)单独的数组?您获得了Article实例,其中分别包含与一篇文章相关的所有内容.

PS: But why for heaven's sake do you map the article instance to – apparently – separate arrays? You got the Article instances which contain everything related to one article respectively.

更多推荐

JSON字符串中出现意外的nil

本文发布于:2023-11-29 23:46:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648001.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   意外   JSON   nil

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!