gpt4 book ai didi

json - Swift JSON 值

转载 作者:行者123 更新时间:2023-11-28 12:17:17 25 4
gpt4 key购买 nike

我是 iOS 开发的新手,需要一些帮助。我有一个来自 Web 服务的 JSON 输出,我想在自定义表格 View 单元格中显示详细信息。实际上,我正在按照这里的教程进行操作:https://www.youtube.com/watch?v=ea6_a_zbQrY

在该教程中,JSON 输出如下:-

{
"actors": [
{
"name": "Brad Pitt",
"description": "William Bradley 'Brad' Pitt is an American actor and film producer. He has received a Golden Globe Award, a Screen Actors Guild Award, and three Academy Award nominations in acting categories",
"dob": "December 18, 1963",
"country": "United States",
"height": "1.80 m",
"spouse": "Jennifer Aniston",
"children": "Shiloh Nouvel Jolie-Pitt, Maddox Chivan Jolie-Pitt",
"image": "http://microblogging.wingnity.com/JSONParsingTutorial/brad.jpg"
},
{
"name": "Tom Cruise",
"description": "Tom Cruise, is an American film actor and producer. He has been nominated for three Academy Awards and has won three Golden Globe Awards. He started his career at age 19 in the 1981 film Endless Love.",
"dob": "July 3, 1962",
"country": "United States",
"height": "1.70 m",
"spouse": "Katie Holmes",
"children": "Suri Cruise, Isabella Jane Cruise, Connor Cruise",
"image": "http://microblogging.wingnity.com/JSONParsingTutorial/cruise.jpg"
},
{
"name": "Johnny Depp",
"description": "John Christopher 'Johnny' Depp II is an American actor, film producer, and musician. He has won the Golden Globe Award and Screen Actors Guild award for Best Actor.",
"dob": "June 9, 1963",
"country": "United States",
"height": "1.78 m",
"spouse": "Lori Anne Allison",
"children": "Lily-Rose Melody Depp, John 'Jack' Christopher Depp III",
"image": "http://microblogging.wingnity.com/JSONParsingTutorial/johnny.jpg"
},

我自己的JSON输出如下:

[{"ID":"5662","Subject":"EXAM [JUNE 17 SEMESTER]","Course":"UNITAR","Lecturer":"EXAM OFFICER","CTime":"9:00AM-5:30PM","Venue":"10.03","TDate":"2017-09-04"},{"ID":"10314","Subject":"FAB","Course":"CAT","Lecturer":"DR CHONG","CTime":"9:00AM-12:00PM","Venue":"THEATRE ROOM 1 [LV 9]","TDate":"2017-09-04"},{"ID":"10317","Subject":"FMA","Course":"CAT","Lecturer":"GS ONG","CTime":"9:00AM-12:00PM","Venue":"9.09","TDate":"2017-09-04"},{"ID":"10318","Subject":"FFA","Course":"CAT","Lecturer":"MARGARET","CTime":"1:00PM-4:00PM","Venue":"THEATRE ROOM 1 [LV 9]","TDate":"2017-09-04"},{"ID":"10319","Subject":"MA1","Course":"CAT","Lecturer":"GS ONG","CTime":"1:00PM-4:00PM","Venue":"9.09","TDate":"2017-09-04"},{"ID":"10320","Subject":"P5","Course":"ACCA","Lecturer":"SPENCER","CTime":"6:15PM-9:45PM","Venue":"THEATRE ROOM 1 [LV 9]","TDate":"2017-09-04"},{"ID":"10324","Subject":"F8","Course":"ACCA","Lecturer":"MIKE KEE","CTime":"6:15PM-9:45PM","Venue":"9.02","TDate":"2017-09-04"},{"ID":"10325","Subject":"F2","Course":"ACCA","Lecturer":"GS ONG","CTime":"6:15PM-9:45PM","Venue":"9.09","TDate":"2017-09-04"},{"ID":"10326","Subject":"F4","Course":"ACCA","Lecturer":"HEMA","CTime":"6:15PM-9:45PM","Venue":"9.13","TDate":"2017-09-04"},{"ID":"11413","Subject":"M4","Course":"TG","Lecturer":"LAI WS","CTime":"7:00PM-10:00PM","Venue":"9.01","TDate":"2017-09-04"}]

下面是教程中的代码,用于解析教程中的 JSON 值:

func downloadJsonWithURL() {
let url = NSURL(string: urlString)
URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
print(jsonObj!.value(forKey: "actors"))

if let actorArray = jsonObj!.value(forKey: "actors") as? NSArray {
for actor in actorArray{
if let actorDict = actor as? NSDictionary {
if let name = actorDict.value(forKey: "name") {
self.nameArray.append(name as! String)
}
if let name = actorDict.value(forKey: "dob") {
self.dobArray.append(name as! String)
}
if let name = actorDict.value(forKey: "image") {
self.imgURLArray.append(name as! String)
}
}
}
}

OperationQueue.main.addOperation({
self.tableView.reloadData()
})
}
}).resume()
}

我如何修改此代码,因为我的 JSON 中没有“actors”键。有人可以指导我如何更改这部分吗?

最佳答案

这是我见过的最糟糕的代码之一。几乎所有的事情都是错误的或者是一个非常糟糕的编程习惯。

最大的错误是:

  • 完全没有错误处理。
  • 使用 Foundation (NSArray/NSDictionary) 而不是原生集合类型。
  • 使用多个字符串数组而不是一个自定义结构/类作为数据模型。
  • 强制解包值而不是安全地处理可选值。
  • 使用 valueForKey 而不是专用的 objectForKey 或 key 订阅。

首先创建一个结构作为数据模型和一个数组作为数据源

struct Schedule {
let id, subject, course, lecturer, cTime, venue, tDate : String
}

var schedules = [Schedule]()

假设所有值都不会改变,结构成员被声明为常量 (let)。您可以免费获得成员初始化器。

读取 JSON 非常容易。只有两种集合类型,数组 ([]) 和字典 ({})。

这个 JSON 是一个字典数组 ([{ .. }, { ...}]) 。所有键和值都是字符串。合适的(原生)Swift 类型是 [[String:String]]。代码解析 JSON 并分配一个空字符串,以防其中一个键不存在。

func downloadJson(with urlString : String) {
guard let url = URL(string: urlString) else { print("bad URL"); return }
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if let connectionError = error {
print(connectionError)
return
}
do {
if let scheduleArray = try JSONSerialization.jsonObject(with: data!) as? [[String:String]] {
for item in scheduleArray {
self.schedules.append(Schedule(id: item["ID"] ?? "",
subject: item["Subject"] ?? "",
course: item["Course"] ?? "",
lecturer: item["Lecturer"] ?? "",
cTime: item["CTime"] ?? "",
venue: item["Venue"] ?? "",
tDate: item["TDate"] ?? ""))
}

DispatchQueue.main.async {
self.tableView.reloadData()
}
}
} catch {
print(error)
}
}
task.resume()
}

cellForRow 的 TableView 中你可以简单地写

 let schedule = schedules[indexPath.row]
aLabel.text = schedule.id
anotherLabel.text = schedule.subject
...

关于json - Swift JSON 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46030186/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com