具有json解码数据错误的For循环要求“People”符合“Sequence”

kqlmhetl  于 2022-11-26  发布在  其他
关注(0)|答案(1)|浏览(137)

我是swift的新手。我创建了简单的playground并将扩展名为json的文件添加到playground中。我尝试使用for循环解码结果并打印ID,但是,我收到以下错误..For-in循环要求“People.Type "符合”Sequence“
这是我的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("// Printing the ID of the Decode Json")

            for jsondata in jsonData {

                print("ID: \(jsonData.id)")
            }
            return jsonData
        } catch {
            print("error:\(error)")
        }
    }
    return nil
}
loadJson(filename: "people1")

下面是错误的屏幕截图。

lc8prwob

lc8prwob1#

在这里,我运行的正是您所要求的,但是我认为您可能应该考虑将您的结构体重命名为像@Vadian建议的Person

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)

            printPeople(people: [jsonData])

            return jsonData
        } catch {
            print("error:\(error)")
        }
    }
    return nil
}

func printPeople(people: [People]) {
    for person in people {
        print(person.id)
        if (!person.options.isEmpty) {
            printPeople(people: person.options)
        }
    }
}

loadJson(filename: "people")

这将打印:

1
11
111
2
21
22
221

相关问题