【发布时间】:2021-06-10 23:16:15
【问题描述】:
我是 swift 新手,我已经根据我输入的示例构建了一个简单的 ui,并且知道它可以工作,但是当我替换自己的数据并编写自己的模型时,它就崩溃了。
我已经检查了我的 JSON,它是有效的。我的 UI 抛出错误 Value of type 'Resorts' has no member 'items'。我遇到的麻烦是使用ForEach 循环遍历json 对象并显示items.resortName
任何帮助都会很大!
这是我的代码:
内容模型
import Foundation
class DataModel: ObservableObject {
@Published var resorts = [Resorts]()
init() {
getLocalData()
}
func getLocalData() {
// Get a url to the json file
let jsonUrl = Bundle.main.url(forResource: "data", withExtension: "json")
do {
// Read the file into a data object
let jsonData = try Data(contentsOf: jsonUrl!)
// Try to decode the json into an array of modules
let jsonDecoder = JSONDecoder()
let resorts = try jsonDecoder.decode([Resorts].self, from: jsonData)
// Assign parsed modules to modules property
self.resorts = resorts
}
catch {
// TODO log error
print("Couldn't parse local data \(error)")
}
}
}
度假村
import Foundation
struct Resorts: Decodable, Identifiable {
var id: Int
var apiVersion: String
var region: Region
}
struct Region: Decodable, Identifiable {
var id: Int
var name: String
var items: [Items]
}
struct Items: Decodable, Identifiable {
var id: Int
var resortName: String
var state: String
}
JSON 片段
[
{
"id":0,
"apiVersion": "12.2",
"region": {
"id": 0,
"name": "Rocky Mountains",
"items": [
{
"id": 0,
"resortName": "A Basin",
"state": "Colorado",
"reportDateTime": "2021-06-05 06:25:00",
"resortStatus": "minutes",
"operationStatus": "8",
...
内容视图
struct ContentView: View {
@EnvironmentObject var model: DataModel
var body: some View {
Text("Hello")
ScrollView {
HStack {
ForEach(model.resorts) { resort in
ZStack {
Color.white
.cornerRadius(8)
VStack {
Text("Resort by name")
// Text(resort.items)
}
}
.frame(width: 175, height: 100)
.shadow(color: Color.black.opacity(0.2), radius: 5, x: 0, y: 0)
}
}
}
}
}
【问题讨论】:
标签: json swift foreach jsondecoder