With JSON
你需要使用JSONDecoder()
。假设我们有这个文件:
[
{
"name": "Banana",
"points": 200,
"description": "A banana grown in Ecuador."
},
{
"name": "Orange",
"points": 100
}
]
为了方便起见,您可以创建一个struct
(即使对于嵌套元素也很方便):
struct product: Codable, Hashable {
var name: String
var points: Int
var description: String?
}
创建一个函数来解析你的JSON
捆绑称为list.json
返回一个array
of struct product
:
func jsonTwo() -> [product]{
let url = Bundle.main.url(forResource: "list", withExtension: "json")!
let data = try! Data(contentsOf: url)
let decoder = JSONDecoder()
let products = try? decoder.decode([product].self, from: data)
return products!
}
最后设置你的界面:
var body: some View {
List{
ForEach(jsonTwo(), id: \.self) { item in
VStack(alignment: .leading, spacing: 0){
Text("name:\(item.name) - points:\(item.points)")
Text("\(item.description ?? "")")
}
}
}
}
完整代码:
struct product: Codable, Hashable {
var name: String
var points: Int
var description: String?
}
struct ContentView: View {
func jsonTwo() -> [product]{
let url = Bundle.main.url(forResource: "list", withExtension: "json")!
let data = try! Data(contentsOf: url)
let decoder = JSONDecoder()
let products = try? decoder.decode([product].self, from: data)
return products!
}
var body: some View {
List{
ForEach(jsonTwo(), id: \.self) { item in
VStack(alignment: .leading, spacing: 0){
Text("name:\(item.name) - points:\(item.points)")
Text("\(item.description ?? "")")
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
![enter image description here](https://i.stack.imgur.com/L7AwC.png)