【发布时间】:2021-10-12 19:22:03
【问题描述】:
假设我正在尝试使用 SwiftUI 解析这个特定的 JSON 文件:
data.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"
}
}
]
我了解如何解析 number 和 word,但我遇到的问题是如何解析 sentence 中的所有内容。我是 iOS 编程新手,我一直在寻找的资源让我感到困惑。这是我到目前为止的代码:
struct Content: Codable, Hashable {
let number: Int
let word: String
}
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: 0) {
Text("\(content.word)")
}
}
}
}
}
}
感谢您的帮助!
【问题讨论】:
-
你的 JSON 数据包含两个字典,不是数字和单词。
-
@ElTomato 我的结构有什么问题吗?
-
您可以将
sentence声明为字典[String:String] -
@Paulw11 我如何在
ContentView上创建带有sentence的文本?会不会是Text("\(content.sentence.word_one)")之类的东西? -
不,您需要获取字典的
keys并对数组进行排序,然后在排序后的数组上迭代键并访问值for key in dictionary.keys.sorted { Text(dictionary[key])之类的东西;我会将键和排序放在模型中的计算变量后面并使用ForEach