Swift 4无法正确解码JSON可选 [英] Swift 4 Not decoding JSON optional properly

查看:103
本文介绍了Swift 4无法正确解码JSON可选的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里快速菜鸟.

我正在尝试遵循《用Swift开发应用程序》一书,并且遇到了如示例中所述从NASA API解码JSON数据时遇到的麻烦.这是我要使用的代码:

I'm trying to follow the App Development With Swift book and am running into trouble with decoding JSON data from the NASA API as given in the examples. Here's the code I'm trying to use:

struct PhotoInfo: Codable {  
    var title: String  
    var description: String  
    var url: URL  
    var copyright: String?  

    enum CodingKeys: String, CodingKey {  
        case title  
        case description = "explanation"  
        case url  
        case copyright  
    }  

    init(from decoder: Decoder) throws {  
        let valueContainer = try decoder.container(keyedBy: CodingKeys.self)  
        self.title = try valueContainer.decode(String.self, forKey: CodingKeys.title)  
        self.description = try valueContainer.decode(String.self, forKey: CodingKeys.description)  
        self.url = try valueContainer.decode(URL.self, forKey: CodingKeys.url)  
        self.copyright = try valueContainer.decode(String.self, forKey: CodingKeys.copyright)  
    }  
}  


func fetchPhotoInfo(completion: @escaping (PhotoInfo?) -> Void) {  
    let baseURL = URL(string: "https:/  
    let query: [String: String] = [  
        "api_key": "yN3**0scRWo12gCa25TWBcfp3rcuAnoeqwbpvLPn",  
        "date": "2011-07-13"  
    ]  
    let url = baseURL.withQueries(query)!  
    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in  
        let jsonDecoder = JSONDecoder()  
        if let data = data,  
            let photoInfo = try? jsonDecoder.decode(PhotoInfo.self, from: data) {  
            print(data)  
            completion(photoInfo)  
        } else {  
            print("Either no data was returned, or data was not properly decoded.")  
            completion(nil)  
        }  
    }  
    task.resume()  
}  

当我从PhotoInfo结构中删除版权代码时,它会解码JSON并打印数据(第36行).否则,它不会反序列化.有什么方法可以解决为什么发生这种情况吗?它与可选项有关吗?

When I remove the copyright code from the PhotoInfo struct, it decodes the JSON and prints the data (line 36). Otherwise, it doesn't deserialize it. Is there a way I can troubleshoot why this is happening? Does it have something to do with the optional?

推荐答案

如果版权是可选的,则可以使用decodeIfPresent.

If copyright is optional , then you can make use of decodeIfPresent.

self.copyright = try valueContainer.decodeIfPresent(String.self, forKey: CodingKeys.copyright)

这篇关于Swift 4无法正确解码JSON可选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆