SwiftUI可找到JSON文件但无法加载数据问题排查
我有一个包含人员信息的JSON文件:
[ { "name": "Mandy", "summary": "This is a summary for person 1", "detail": "This is a detailed description for person 1", "category": "Leaders" },
对应的Person和Category模型如下:
struct Person: Identifiable, Decodable { var id: UUID = UUID() var name: String var summary: String var detail: String var category: Category } enum Category: String, CaseIterable, Codable { case leaders = "Leaders" case competitors = "Competitors" case thinkers = "Thinkers" case explorers = "Explorers" }
我写了DataLoader类用来加载JSON数据(预览时用模拟数据):
class DataLoader: ObservableObject { @Published var people: [Person] = [] init(preview: Bool = false) { if preview { // SwiftUI预览用模拟数据 people = [ Person(name: "Preview Leader", summary: "Leader Summary", detail: "Detail about the Leader", category: .leaders), Person(name: "Preview Competitor", summary: "Competitor Summary", detail: "Detail about the Competitor", category: .competitors), Person(name: "Preview Thinker", summary: "Thinker Summary", detail: "Detail about the Thinker", category: .thinkers), Person(name: "Preview Explorer", summary: "Explorer Summary", detail: "Detail about the Explorer", category: .explorers) ] } else { // 实际运行时加载JSON guard let url = Bundle.main.url(forResource: "people", withExtension: "json") else { fatalError("Could not find file in bundle") } do { let data = try Data(contentsOf: url) print("Data loaded successfully: \(data)") let decodedData = try JSONDecoder().decode([Person].self, from: data) self.people = decodedData print("Decoded data: \(decodedData)") } catch { print("Error while parsing: \(error)") } } } }
视图中通过环境对象观察DataLoader:
struct ContentView: View { @EnvironmentObject var dataLoader: DataLoader @State private var selectedTab = 0 var body: some View{.....
App.swift中的配置:
struct myApp: SwiftUI.App { @StateObject private var dataLoader = DataLoader(preview: false) // 实际运行设为false var body: some Scene { WindowGroup { ContentView() .environmentObject(dataLoader) } } }
更新1
我在DataLoader初始化里加了路径打印,但控制台没有任何输出:
let bundle = Bundle.main if let path = bundle.path(forResource: "people", ofType: "json") { print("people.json file path: \(path)") } else { print("people.json file not found in bundle.") }
更新2
切换到Xcode调试控制台的“所有输出”后,看到了解析错误:
Error while parsing: dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription:"The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840"Badly formed object around line 4, column 8."UserInfo={NSDebugDescription=Badly formed object around line 4, column 8., NSJSONSerializationErrorIndex=36})))
但在线JSON验证工具显示我的JSON格式正确,请问问题出在哪?
你的JSON文件存在核心语法问题,同时还有项目文件验证的注意点:
JSON数组未闭合且存在多余逗号
你提供的JSON代码中,数组开头是[但没有对应的]结尾,并且最后一个对象后多了逗号,,这会直接导致解析失败。修正后的完整JSON示例:[ { "name": "Mandy", "summary": "This is a summary for person 1", "detail": "This is a detailed description for person 1", "category": "Leaders" } ]若有多个对象,格式应为:
[ { "name": "Mandy", "summary": "This is a summary for person 1", "detail": "This is a detailed description for person 1", "category": "Leaders" }, { "name": "Another Person", "summary": "Summary 2", "detail": "Detail 2", "category": "Competitors" } ]项目中JSON文件内容可能和你提供的不一致
在线验证工具显示正确,大概率是你粘贴到工具中的内容已经修正,但项目里的people.json实际还有语法错误。建议直接打开项目内的JSON文件,检查:- 数组是否有完整的
[和] - 对象末尾是否有多余的逗号
- 所有引号是否为英文双引号(无中文引号)
- 数组是否有完整的
控制台无输出的排查
- 确保Xcode调试控制台选择了“所有输出”(而非仅“调试输出”)
- 在
DataLoader的init开头添加print("DataLoader init called with preview: \(preview)"),确认初始化逻辑是否执行
增加数据加载校验
可以在解析前打印加载的原始JSON内容,确认文件是否正确读取:do { let data = try Data(contentsOf: url) if let jsonString = String(data: data, encoding: .utf8) { print("Loaded JSON content:\n\(jsonString)") } let decodedData = try JSONDecoder().decode([Person].self, from: data) self.people = decodedData } catch { print("Error while parsing: \(error)") }
内容的提问来源于stack exchange,提问作者nc14

