我有一个JSON数据,我想在Swift 1.2中解析它。 我找到了这篇文章,它给了我很多帮助:http://www.learnswift.io/blog/2015/3/4/populating-a-uitableview-with-json
但是在本教程中,JSON文件与我的文件略有不同:https://api.github.com/search/repositories?q=learn+swift+language:swift&sort=stars&order=desc
(有“项目”数组)
这是我的:(我想显示所有行:row0,row1 ......)
{
"headers": {
"NOTE_ID": "NOTE_ID",
"NOTE_NAME": "NAME",
"SUBJECT": "SUBJECT"
},
"row0": {
"NOTE_ID": "45680",
"NOTE_NAME": "Do not go there",
"SUBJECT": "Manchester"
},
"row1": {
"NOTE_ID": "45681",
"NOTE_NAME": "Watch TV",
"SUBJECT": "Football game"
},
"info": {
"PageCounter": 17,
"NoteCounter": "1670"
}
}
我知道我需要更改此部分,因为教程中的JSON有一个“items”数组,所以它包含在那里:
if let reposArray = json["items"] as? [NSDictionary] {
// 5
for item in reposArray {
repositories.append(Repository(json: item))
}
}
完整代码:
override func viewDidLoad() {
super.viewDidLoad()
// 1
let reposURL = NSURL(string: "https://www.example.com/api/notes")
// 2
if let JSONData = NSData(contentsOfURL: reposURL!) {
// 3
if let json = NSJSONSerialization.JSONObjectWithData(JSONData, options: nil, error: nil) as? NSDictionary {
// 4
if let reposArray = json["items"] as? [NSDictionary] {
// 5
for item in reposArray {
repositories.append(Repository(json: item))
}
}
}
}
}
任何人都可以帮助我吗? 非常感谢提前。
答案 0 :(得分:0)
很难说,因为你既没有items
条目,也没有数组。这是一个字典,其中每个值本身就是另一个字典。
所以,你可以这样做:
if let reposDictionary = json as? [String: [String: AnyObject]] {
// do something with `reposDictionary`, e.g.,
//
// for (key, value) in reposDictionary { ... }
}
或者,如果您想使用NSDictionary
而不是Swift词典:
if let reposDictionary = json as? NSDictionary { ... }
-
顺便说一句,如果这些行的顺序很重要,你就不应该使用字典(这是无序的),而应该更改JSON以便它真正返回一个数组:
{
"headers": {
"NOTE_ID": "NOTE_ID",
"NOTE_NAME": "NAME",
"SUBJECT": "SUBJECT"
},
"items": [
{
"row0": {
"NOTE_ID": "45680",
"NOTE_NAME": "Do not go there",
"SUBJECT": "Manchester"
}
},
{
"row1": {
"NOTE_ID": "45681",
"NOTE_NAME": "Watch TV",
"SUBJECT": "Football game"
}
}
],
"info": {
"PageCounter": 17,
"NoteCounter": "1670"
}
}
或者,更好:
{
"headers": {
"NOTE_ID": "NOTE_ID",
"NOTE_NAME": "NAME",
"SUBJECT": "SUBJECT"
},
"items": [
{
"NOTE_ID": "45680",
"NOTE_NAME": "Do not go there",
"SUBJECT": "Manchester"
},
{
"NOTE_ID": "45681",
"NOTE_NAME": "Watch TV",
"SUBJECT": "Football game"
}
],
"info": {
"PageCounter": 17,
"NoteCounter": "1670"
}
}
所以要有一个包含headers
和info
的字典,但要使items
成为一个数组。现在您可以使用以下语法:
if let reposArray = json["items"] as? [NSDictionary] { ... }