【问题标题】:Displaying a list of arrays from Json in Swift [closed]在 Swift 中显示来自 Json 的数组列表 [关闭]
【发布时间】:2021-08-24 12:48:02
【问题描述】:

我有一个 Json 文件,其中列出了按类别排序的书籍。

{
  "FullBookList": [
    {
      "Fantasy": [
        {
          "title": "Alice's Adventures in Wonderland",
          "author": "Lewis Carrol"
        }
      ],
      "Fiction": [
        {
          "Title": "Hamlet",
          "Author": "Maggie O'Farrel"
        }
      ],
      "Comedy": [
        {
          "Title": "Good Omans",
          "Author": "Neil Gaiman"
        }
      ]
    }
  ]
}

我正在尝试让 swiftui 创建一个“FullBookList”数组列表,以便它列出...

  1. 奇幻>
  2. 小说>
  3. 喜剧 >

有什么帮助吗?我希望我已经解释清楚了。 导入基金会

struct BookCategory: Decodable {
    let FullBookList: [FullBookList]
}

struct FullBookList: Decodable {
    let Fantasy: [Books]
}

struct Books: Decodable {
    let title: String
    let author: String
}

class BookJson: ObservableObject {

    func GetBookList() {
        do {
            let json = Bundle.main.url(forResource: "Books", withExtension: "json")
            let jsonData = try Data(contentsOf: json!)
            let book = try! JSONDecoder().decode(BookCategory.self, from: jsonData)
            DispatchQueue.main.async {
                print(book.FullBookList) //???
                    }
        } catch {
            print("oof")
        }
    }

}

【问题讨论】:

标签: arrays json swift


【解决方案1】:

首先把 JSON 的结构改成这样,因为这样更容易解析

{
    "categories": [
        {
        "name": "Fantasy",
        "books": [
            {
                "title": "Alice's Adventures in Wonderland",
                "author": "Lewis Carrol"
            }
        ]
        },{
        "name": "Fiction",
        "books": [
            {
                 "title": "Hamlet",
                 "author": "Maggie O'Farrel"
            }
        ]
        },{
        "name": "Comedy",
        "books": [
            {
                 "title": "Good Omans",
                 "author": "Neil Gaiman"
            }
        ]
        }
    ]
}

对应的结构体是

struct BookData: Decodable {
    let categories: [Category]
}

struct Category: Decodable {
    let name : String
    let books: [Book]
}

struct Book: Decodable, Identifiable {
    private enum CodingKeys : String, CodingKey { case title, author }
    
    let id = UUID()
    let title: String
    let author: String
}

ObservableObject 类中添加一个@Published 属性,它将通知更改

class BookController : ObservableObject {
    
    @Published var categories = [Category]()

    func loadData() {
        let url = Bundle.main.url(forResource: "Books", withExtension: "json")!
        let data = try! Data(contentsOf: url)
        do {
            let bookData = try JSONDecoder().decode( BookData.self, from: data)
            DispatchQueue.main.async {
                self.categories = bookData.categories
            }
        } catch {
            print(error)
        }
    }
}

在视图中加载数据 onAppear 并构建 UI

struct ContentView : View {
    @StateObject var bookController = BookController()
    
    var body: some View {
        List {
            ForEach(bookController.categories, id: \.name) { category in
                Section(header: Text(category.name)) {
                    ForEach(category.books) { book in
                        HStack {
                            Text(book.author)
                            Spacer()
                            Text(book.title)
                        }
                    }
                }
           }
        }
        .onAppear() {
            bookController.loadData()
        }
    }
}

【讨论】:

  • 非常感谢!我认为更改 JSON 以使其更简单会产生奇迹。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多