首页 > 解决方案 > 如何快速从本地 JSON 文件中获取数据?

问题描述

我想从本地 JSON 文件中获取数据。它看起来像:

[
[
{
  "link": "link1",
  "answers": [
    "answer1",
    "answer2",
    "answer3",
    "answer4",
    "answer5"
  ],
  "questions": "question1"
},
{
  "link": "link2",
  "answers": [
    "answer1",
    "answer2",
    "answer3",
    "answer4",
    "answer5"
  ],
  "questions": "question2"
}
]
]

我怎样才能分开每个元素?我怎样才能分别回答每个答案?我想在表格视图中使用答案。indexPath.row[1] = answer1 indexPath.row[2] = answer2...

let url = Bundle.main.url(forResource: "info", withExtension: "json")!
    do {
        let jsonData = try Data(contentsOf: url)
        let json = try JSONSerialization.jsonObject(with: jsonData)
        print(json)

        //let current = json["title"] as! [String: [String:Any]]

        //for (key, currency) in current {
            //let quest = currency["title"] as! String
            //let img = currency["image"] as! String
            //let ans = currency["answers"] as! [String]
        //}
    }
    catch {
        print(error)
    }

}

标签: jsonswiftparsingtableview

解决方案


您必须注意JSON结构以获得正确的值。请参阅以下代码段,了解如何在JSON.

    let url = Bundle.main.url(forResource: "File", withExtension: "txt")!
    do {
        let jsonData = try Data(contentsOf: url)
        let json = try JSONSerialization.jsonObject(with: jsonData) as! [[[String: Any]]]

        if let question1 = json.first?[0] {
            print( question1["link"] as! String)
        }

        if let question2 = json.first?[1] {
            print( question2["link"] as! String)
        }
    }
    catch {
        print(error)
    }

所以现在,您知道如何获取实际数据了。你应该创建一些Question类。然后,您应该保留从文件中解析的问题列表,并将该列表用于您的TableView.


推荐阅读