ios - SwiftUI-从JSON文件显示数组

标签 ios arrays json swift swiftui

对SwiftUI来说是非常新的东西,我在很短的时间内就学到了很多东西。我正在努力的一件事是使用循环显示JSON文件中的数组。我希望有人可以帮助我!
抱歉,如果这是一个 super n00b问题,我已经搜索了很多东西,但似乎找不到如何显示此内容的示例或答案(否则,我可能正在尝试错误的方法)
这是我的JSON对象的示例

{
"name": "Name of Spot",
"city": "City of Spot",
"state": "State of Spot",
"id": 1001,
"description": "Description of Spot",
"imageName": "imageName",
"categories": [
   {
   "category": "Category Name 1"
   },
   {
   "category": "Category Name 2"
   },
   {
    "category": "Category Name 3"
    }
   ]
}
这是我当前的数据模型
struct Spot: Hashable, Codable, Identifiable {
    var id: Int
    var name: String
    fileprivate var imageName: String
    var city: String
    var state: String
    var description: String
我想做的是创建一个显示每个类别的文本字符串的循环。我不知道如何将数组添加到我的结构或如何创建将显示它们的循环。我设法创建了循环来获取每个“地点”,并动态提取其余信息,而不是类别。
提前致谢!
编辑:这是我收到错误的示例
struct TestArray: View {
    
    var spot: Spot
    
    var body: some View {
        VStack {
            spot.categories.forEach { (category) in
                Text(category["category"] ?? "n/a")
            }
        }

    }
}

最佳答案

您可以创建一个Category对象,然后将category声明为该对象的数组。如果要在不创建仅具有一个属性的新对象的情况下执行此操作,则也可以只使用包含String作为键值的Dictionary数组。

struct Spot: Hashable, Codable, Identifiable {
    var id: Int
    var name: String
    fileprivate var imageName: String
    var city: String
    var state: String
    var description: String
    var categories: [Category]
}

struct Category: Codable {
    var category: String
}
如果要使用字典数组代替:
struct Spot: Hashable, Codable, Identifiable {
    ...
    var categories: [[String: String]]
    ...
}
编辑:
要迭代并显示Dictionary数组中的类别,假设您的Spot对象被命名为spot,您应该能够做到这一点:
VStack {
    spot.categories.forEach { (category) in
        Text(category["category"] ?? "n/a")
    }
}

关于ios - SwiftUI-从JSON文件显示数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63618554/

相关文章:

php - PHP 中的 MySQL 数据按日期时间对 JSON 数据进行排序

ios - 如何获取ios 9中的数据模型?

arrays - 所有可能的骑士在普罗梅拉的棋盘上移动

java - 使用插入排序、选择排序和归并排序进行排序

python - 在 numpy 数组中找到平衡点

javascript - 通过nodejs过滤对象数组

json - Pinterest API 图像大小

ios - UIButtonBarItem 没有改变

ios - 从 UILabel 更改 LineBreak 字符

ios - 防止我自己的应用程序的共享扩展出现在共享表中