【发布时间】:2017-01-25 13:58:13
【问题描述】:
我想在 tableview 中显示我的数据,我有一个 json 数据,我已经看过这个 tutorial。它正在工作,但我的 json 数据没有数组键“actor”。 这是示例的 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"
}
]
}
这是我的 json 数据。
[
{
"ID": 1,
"name": "Amy"
{
"ID": 2,
"name": "John"
}
]
这是我的代码;
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 studentArray = jsonObj!.value(forKey: "actors") as? NSArray {
for student in studentArray{
if let studentDict = student as? NSDictionary {
if let name = studentDict.value(forKey: "ID") {
self.noArray.append(name as! String)
}
if let name = studentDict.value(forKey: "name") {
self.adiArray.append(name as! String)
}
}
}
}
OperationQueue.main.addOperation({
self.tableView.reloadData()
})
}
}).resume()
}
我这里有问题; enter image description here
这将是一个问题:/
// my json data doesnt have "actors" ?????
print(jsonObj!.value(forKey: "actors"))
if let studentArray = jsonObj!.value(forKey: "actors") as? NSArray {
for student in studentArray{
if let studentDict = student as? NSDictionary {
【问题讨论】:
-
不要强制解包
!