我对获取水果的细节感到困惑
I am confusing to getting detail of fruit
{ "fruits": [ { "id": "1", "image": "cdn1.medicalnewstoday/content/images/headlines/271/271157/bananas.jpg", "name": "Banana" }, { "id": "2", "image": "soappotions/wp-content/uploads/2017/10/orange.jpg", "title": "Orange" } ] }想使用可解码"解析JSON
Want to parse JSON using "Decodable"
struct Fruits: Decodable { let Fruits: [fruit] } struct fruit: Decodable { let id: Int? let image: String? let name: String? } let url = URL(string: "www.JSONData/fruits") URLSession.shared.dataTask(with: url!) { (data, response, error) in guard let data = data else { return } do{ let fruits = try JSONDecoder().decode(Fruits.self, from: data) print(Fruits) }catch { print("Parse Error") }还可以建议我cocoapod库来快速下载图像
also can you please suggest me cocoapod library for fastly download images
推荐答案您面临的问题是因为JSON返回的水果数据不同.
The issue you are facing is because your JSON is returning different data for your Fruits.
对于第一个ID,它返回一个称为name的String,但是在第二个ID中,它返回一个称为title的字符串.
For the 1st ID it returns a String called name, but in the 2nd it returns a String called title.
此外,在解析JSON时,ID似乎是String而不是Int.
In addition when parsing the JSON the ID appears to be a String and not an Int.
因此,您的数据中有两个可选值.
Thus you have two optional values from your data.
因此,可分解结构"应如下所示:
As such your Decodable Structure should look something like this:
struct Response: Decodable { let fruits: [Fruits] } struct Fruits: Decodable { let id: String let image: String let name: String? let title: String? }由于您的网址似乎无效,因此我在主捆绑包中创建了JSON文件,并能够像这样正确解析它:
Since your URL doesn't seem to be valid, I created the JSON file in my main bundle and was able to parse it correctly like so:
/// Parses The JSON func parseJSON(){ if let path = Bundle.main.path(forResource: "fruits", ofType: "json") { do { let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe) let jsonResult = try JSONDecoder().decode(Response.self, from: data) let fruitsArray = jsonResult.fruits for fruit in fruitsArray{ print(""" ID = \(fruit.id) Image = \(fruit.image) """) if let validName = fruit.name{ print("Name = \(validName)") } if let validTitle = fruit.title{ print("Title = \(validTitle)") } } } catch { print(error) } } }希望有帮助...
更多推荐
如何使用Swift 4解析JSON
发布评论