如何使用 swift 4 解析 JSON

2024-02-21

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

{
  "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"
    }
  ]
}

想要使用“Decodable”解析 JSON

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 库来快速下载图像吗


您面临的问题是因为您的JSON正在为您的水果返回不同的数据。

对于第一个 ID,它返回一个String called name,但在第二个中它返回一个名为的字符串title.

此外,在解析 JSON 时,ID 似乎是String而不是一个Int.

因此,您的数据有两个可选值。

因此,您的可解码结构应该如下所示:

struct Response: Decodable {
    let fruits: [Fruits]

}

struct Fruits: Decodable {
    let id: String
    let image: String
    let name: String?
    let title: String?
}

由于您的 URL 似乎无效,因此我在主包中创建了 JSON 文件,并且能够正确解析它,如下所示:

/// 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)
        }
    }
}

希望能帮助到你...

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 swift 4 解析 JSON 的相关文章

随机推荐