JSON字符串中出现意外的nil

时间:2017-10-17 16:32:53

标签: json swift null

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

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 ?? "https://static.wixstatic.com/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])

                        }

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

  

FC91DEECC1631350EFA71C9C561D).description],debugDescription:"预期字符串值但是找到了null。",underlyingError:nil))

注意:

此JSON适用于其他不具有nil值的网址。

这里是json

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

2 个答案:

答案 0 :(得分:7)

错误很明显。 JSONDecoderNSNull映射到nil,以便解码器在将nil值解码为非可选类型时会抛出错误。

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

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

或自定义解码器以用空字符串替换nil

由于JSONDecoderNSNull映射到nil,因此支票if ... == NSNull.self {无用。

编辑:

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

 let response =  try JSONDecoder().decode(Response.self , from : data)
 for article in response.articles {
      beforeLoadNewsViewController.titleArray.append(article.title)
 }
PS:但是为什么天堂的缘故你将文章实例映射到 - 显然 - 单独的数组?您得到的Article个实例分别包含与一篇文章相关的所有内容。

答案 1 :(得分:0)

对不起,我还不能发表评论。但是你为什么不测试“null”的方式,你在URLSession数据检查中使用guard-statement进行了测试?

然后看起来像:

guard let title = article.articles[i].title else {
    beforeLoadNewsViewController.titleArray.append("")
    return
}
beforeLoadNewsViewController.titleArray.append(title)

您尝试在此处解析JSON结构,以防JSON结构不符合您的需求,您仍然希望它具有相应的属性。

您是否还可以提供JSON结构以及解码方式

try JSONDecoder().decode(Response.self , from : data)

看起来像?