小编典典

如何使用Swift 4解析JSON

swift

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

{
  "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库快速下载图像


阅读 324

收藏
2020-07-07

共1个答案

小编典典

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

对于第一个ID,它返回一个Stringname,但在第二个它返回一个字符串叫title

另外,在解析JSON时,ID似乎是a String而不是Int

因此,您可以从数据中获得两个可选值。

因此,“可分解结构”应如下所示:

struct Response: Decodable {
    let fruits: [Fruits]

}

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

由于您的网址似乎无效,因此我在主捆绑包中创建了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)
        }
    }
}

希望能帮助到你…

2020-07-07