使用Swift 4进行JSON解析

时间:2017-12-18 13:32:01

标签: json parsing swift4

我是一个全新的网络和解析我花了两天时间试图弄清楚如何显示这个api中的项目http://api.alquran.cloud/quran/en.asad 例如,我需要所有的名称或api中的任何对象我有0知识,我尝试上网寻求解决方案我无法找到我的情况他是我的代码:

struct Result: Codable {
    var number: [String:Int]
    var text: [String:String]
}

struct Surahs: Codable {
var data: Surah

}

 struct Surah: Codable {
var surahs: [SurahItem]

}

 struct SurahItem: Codable {
var number: Int?
var text: String?

}

    enum CodingKey:String, Swift.CodingKey {
case name = "name"
case text = "text"
case number = "number"

}

   import UIKit
   class afasyVC: UIViewController {

func jsonDecoding() {
    let jsonUrlString = "http://api.alquran.cloud/quran/en.asad"

    guard let url = URL(string: jsonUrlString) else {return}
    URLSession.shared.dataTask(with: url) { (data, response, err) in
        guard let data = data else {return}
        do {
            let quraanJsonStuff =  try JSONDecoder().decode(SurahItem.self, from: data)
            for numbers in [quraanJsonStuff] {
                print(quraanJsonStuff)
            }
            } catch let jsonErr {
            print("Error serializing json", jsonErr)
        }
        }.resume()
}

1 个答案:

答案 0 :(得分:1)

Swift 4中的JSONDecoder转换JSON集合类型如下:

  • 到Swift结构/类的JSON字典{}
  • 一个JSON数组[]到Swift数组。

根据JSON,结构是

struct Root: Codable {
    let code: Int
    let status: String
    let data : Surah
}

struct Surah: Codable {
    let surahs: [SurahItem]
}

struct SurahItem: Codable {
    let number: Int
    let name: String
    let englishName : String 
    // ... and so on
}

在根对象中有一个键data字典,其中包含键surahs的数组

解码并打印SurahItem数组写

let root =  try JSONDecoder().decode(Root.self, from: data)
for surah in root.data.surahs {
     print(surah.number, surah.name, surah.englishName)
}