Let's say I'm trying to parse this particular JSON file with SwiftUI:
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"
}
}
]
I understand how to parse number and word, but what I'm having trouble with is how to parse everything in sentence. I am new to iOS programming and the resources I've been looking at are confusing to me. This is the code I have thus far:
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)")
}
}
}
}
}
}
Thank you for your help!
sentenceas a dictionary[String:String]sentenceon theContentView? Would it be something likeText("\(content.sentence.word_one)")?keysof the dictionary and sort the array and then iterate over the sorted array for keys and access the valuefor key in dictionary.keys.sorted { Text(dictionary[key])kind of thing; I would put the keys and sorting behind a computed variable in your model and useForEach