Swift 4无法正确解码JSON

时间:2017-11-30 05:09:49

标签: json swift

Swift noob在这里。

我正在尝试使用Swift预订App开发,并且在解码来自NASA API的JSON数据时遇到了麻烦,如示例中所示。这是我正在尝试使用的代码:

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行)。否则,它不会反序列化它。有没有办法可以解决为什么会发生这种情况?它与可选项有关吗?

2 个答案:

答案 0 :(得分:2)

如果版权是可选的,那么您可以使用decodeIfPresent

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

答案 1 :(得分:-2)

编辑: 根据@matt的评论进行更新。

technerd的答案可能是最好的,但是我遇到了同样的问题,并通过将try更改为try?来解决。无论如何,这就是以前的练习中提出的方式。但是,正如@matt所指出的那样,这并不能解决版权信息并非简单丢失的可能性,而实际上不是所期望的。结合使用try?if let语句至少可以提供基本的反馈。