Json解码结果正在打印到swift playground中的控制台

ve7v8dk2  于 2022-11-26  发布在  Swift
关注(0)|答案(1)|浏览(125)

我是swift的新手。我创建了简单的playground并将扩展名为json的文件添加到playground中。我试图解码结果并将ID打印到控制台中,但任何原因,它都没有将结果打印到控制台中,我在控制台窗口中没有看到错误
下面是操场项目结构图..

这是我的json文件。

let json = """
{
 "id": "1",
 "options": [
 {
 "id": "11",
 "options": [
 {
 "id": "111",
 "options": []
 }
 ]
 },
 {
 "id": "2",
 "options": [
 {
 "id": "21",
 "options": []
 },
 {
 "id": "22",
 "options": [
 {
 "id": "221",
 "options": []
 }
 ]
 }
 ]
 }
 ]
}

这里是代码..我试过..

struct People: Codable {
    let id: String
    let options: [People]
}
func loadJson(filename fileName: String) -> People? {
    if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
        do {
            let data = try Data(contentsOf: url)
            let decoder = JSONDecoder()
            let jsonData = try decoder.decode(People.self, from: data)
            print(jsonData.id)
            return jsonData
        } catch {
            print("error:\(error)")
        }
    }
    return nil
}

不打印解码json的ID ..

qvtsj1bj

qvtsj1bj1#

因此,我确实让它打印ID,我将people文件名更改为people.json,并将内容更改为:

{
    "id": "1",
    "options": [{
            "id": "11",
            "options": [{
                "id": "111",
                "options": []
            }]
        },
        {
            "id": "2",
            "options": [{
                    "id": "21",
                    "options": []
                },
                {
                    "id": "22",
                    "options": [{
                        "id": "221",
                        "options": []
                    }]
                }
            ]
        }
    ]
}

(请注意,我删除了let json =语句。)
然后,在定义People结构体和loadJson方法的地方,可以这样调用它:

loadJson(filename: "people")

因此,现在您将得到:

struct People: Codable {
    let id: String
    let options: [People]
}

func loadJson(filename fileName: String) -> People? {
    if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
        do {
            let data = try Data(contentsOf: url)
            let decoder = JSONDecoder()
            let jsonData = try decoder.decode(People.self, from: data)
            print(jsonData.id)
            return jsonData
        } catch {
            print("error:\(error)")
        }
    }
    return nil
}

loadJson(filename: "people")

相关问题