在SwiftUI中如何解析包含嵌套sentence结构的特定JSON文件
解决方案
1. 修正data.json的语法错误
你提供的JSON文件存在语法问题:sentence 嵌套对象内的多个键值对之间缺少逗号,会直接导致解析失败,修正后的完整JSON如下:
[ { "number": 1, "word": "hello", "sentence": { "word_one": "my", "word_two": "name", "word_three": "is", "word_four": "jeff" } }, { "number": 2, "word": "there", "sentence": { "word_one": "i", "word_two": "dream", "word_three": "about", "word_four": "cheese" } } ]
2. 新增嵌套结构体匹配JSON结构
Codable解析嵌套结构时,需要为每一层嵌套对象定义对应的模型,你需要新增Sentence结构体对应JSON里的嵌套sentence字段,调整后的完整模型代码如下:
// 对应嵌套的sentence结构 struct Sentence: Codable, Hashable { let word_one: String let word_two: String let word_three: String let word_four: String } struct Content: Codable, Hashable { let number: Int let word: String // 新增sentence属性 let sentence: Sentence }
3. 调整视图展示逻辑
解析逻辑不需要改动,直接在列表中取出content.sentence的属性展示即可,完整的视图代码如下:
struct ContentView: View { func jsonParse() -> [Content] { let url = Bundle.main.url(forResource: "data", withExtension: "json")! let data = try! Data(contentsOf: url) let decoder = JSONDecoder() let products = try? decoder.decode([Content].self, from: data) return products! } var body: some View { NavigationView { List { ForEach(jsonParse(), id: \.self) { content in VStack(alignment: .leading, spacing: 4) { Text(content.word) .font(.headline) // 拼接展示sentence的完整内容 Text("\(content.sentence.word_one) \(content.sentence.word_two) \(content.sentence.word_three) \(content.sentence.word_four)") .font(.subheadline) .foregroundColor(.secondary) } } } .navigationTitle("解析结果") } } }
注:后续你可以补充错误处理逻辑替换强制解包,避免JSON异常时App直接崩溃;也可以通过CodingKeys把JSON里的下划线命名转换为Swift常用的驼峰命名,符合代码规范。
内容的提问来源于stack exchange,提问作者MohAliBou
相关产品推荐
相关产品推荐

