如何使用Swift 4解析JSON [英] How to parse JSON using swift 4

查看:84
本文介绍了如何使用Swift 4解析JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am confusing to getting detail of fruit

{
  "fruits": [
    {
      "id": "1",
      "image": "https://cdn1.medicalnewstoday.com/content/images/headlines/271/271157/bananas.jpg",
      "name": "Banana"
    },
    {
      "id": "2",
      "image": "http://soappotions.com/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: "https://www.JSONData.com/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,它返回一个称为nameString,但是在第二个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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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