如何使用Swift 4解析JSON

编程入门 行业动态 更新时间:2024-10-04 17:23:59
本文介绍了如何使用Swift 4解析JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我对获取水果的细节感到困惑

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

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

发布评论

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

>www.elefans.com

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