本文介绍了使用Swift 4进行JSON解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对网络和解析是全新的.我已经连续两天试图弄清楚如何显示来自此 api .例如,我需要所有我不知道的api的名称或对象,并且尝试在Internet上冲浪以找到我无法找到的解决方案.这是我的代码:
Im totally new to networking and parsing. I have spent 2 straight days trying to figure out how I can display the items from this api. For example I need all the names or any object from the api I have zero knowledge and I tried surfing the internet for a solution I cant find for my case. Here is my code:
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 = "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() } }推荐答案
Swift 4中的JSONDecoder如下转换JSON集合类型:
The JSONDecoder in Swift 4 transforms the JSON collection types as follows:
- 到Swift结构/类的JSON字典{}.
- JSON数组[]到Swift数组.
- A JSON dictionary {} to a Swift struct / class.
- A JSON array [] to a Swift array.
根据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的数组
In the root object there is a dictionary for key data which contains the array for key surahs
要解码和打印SurahItem数组写入
let root = try JSONDecoder().decode(Root.self, from: data) for surah in root.data.surahs { print(surah.number, surah.name, surah.englishName) }更多推荐
使用Swift 4进行JSON解析
发布评论