首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Swift JSON值

Swift JSON值
EN

Stack Overflow用户
提问于 2017-09-04 04:12:34
回答 4查看 189关注 0票数 0

我是iOS开发新手,这里需要一些帮助。我有一个来自webservice的JSON输出,我希望在自定义表视图单元格中显示详细信息。实际上,我在这里学习一个教程:zbQrY

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

代码语言:javascript
复制
{
  "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输出如下:

代码语言:javascript
复制
[{"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值的代码:

代码语言:javascript
复制
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“键。有人能指导我如何改变这个部分吗?

EN

回答 4

Stack Overflow用户

发布于 2017-09-04 05:19:38

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

最大的错误是:

  • 根本没有错误处理。
  • 基金会(NSArray / NSDictionary)而不是本机集合类型的使用。
  • 使用多个字符串数组而不是一个自定义结构/类作为数据模型。
  • 强制展开值,而不是安全地处理选项。
  • 使用valueForKey而不是专用objectForKey或密钥订阅。

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

代码语言:javascript
复制
struct Schedule {
    let id, subject, course, lecturer, cTime, venue, tDate : String
}

var schedules = [Schedule]()

假设不会更改所有值,则struct成员被声明为常量(let)。您可以免费获得按成员划分的初始化程序。

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

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

代码语言:javascript
复制
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的表视图中,您可以简单地编写

代码语言:javascript
复制
 let schedule = schedules[indexPath.row]
 aLabel.text = schedule.id
 anotherLabel.text = schedule.subject
 ...
票数 2
EN

Stack Overflow用户

发布于 2017-09-04 04:28:23

在本教程中,作者的数据格式是数组字典,每个数组都是类型字典,因此,在代码中,首先作者将json数据转换为NSDictionary,然后使用actor关键字访问数组。

但在您的情况下,所有这些步骤都是不必要的,因为您的数据直接位于字典数组中。因此,首先将数据转换为NSArray,然后将数据的每个记录转换为NSDictionary,如下代码片段所示。

代码语言:javascript
复制
func downloadJsonWithURL() {
     let url = URL(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?  [[String:String]] {
        print(jsonObj)

                for student in jsonObj{
                    if let studentDict = student as? [String:String] {
                        if let id = studentDict["ID"] ?? "" {
                            self.idArray.append(id)
                        }
                        if let subject = actorDict["Subject"] ?? "" {
                            self.subArray.append(subject)
                        }
                    }
                }
            OperationQueue.main.addOperation({
                self.tableView.reloadData()
            })
        }
    }).resume()
}
票数 0
EN

Stack Overflow用户

发布于 2017-09-04 04:34:38

首先,忽略JSON内容,而是将其看作一个名为course的对象数组。

代码语言:javascript
复制
[
    {
        "ID": "",
        "Subject": "",
        "Course": "",
        "Lecturer": "",
        "CTime": "",
        "Venue": "",
        "TDate": ""
    },

    ...
]

因此,首先需要将JSON解析为数组。让我们把它叫做coursesArray

代码语言:javascript
复制
if let coursesArray = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSArray
{
    for course in CoursesArray
    {
        // course is a json object. So get it into a dictionary so that
        // we can access the values in the course.

        if let courseDict = course as? NSDictionary
        {
            // Now we can print the remaining properties of the course
            let id = courseDict.value(forKey: "ID")
            let subject = courseDict.value(forKey: "Subject")
            let courseName = courseDict.value(forKey: "Course")
            let lecturer = courseDict.value(forKey: "Lecturer")
            let cTime = courseDict.value(forKey: "CTime")
            let venue = courseDict.value(forKey: "Venue")
            let tDate = courseDict.value(forKey: "TDate")

            // Print them, or use them in any way you like now.
        }
    }
}

这应该适用于数据的提取。为了能够使用这些,您需要将它们附加到其他数组中,并重新加载表。我把它留给你。

希望这能有所帮助。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46030186

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档