Restaurant Menu Viewer JSON Parser

This commit is contained in:
Ingo Rohlf 2025-10-24 15:04:47 +02:00
parent b91ab9d571
commit a01a6d9f26
3 changed files with 20 additions and 13 deletions

View file

@ -14,13 +14,14 @@ struct MenuCard: Codable {
struct MenuItem: Codable { struct MenuItem: Codable {
let name: String let name: String
let detailText: String let description: String
let imageUrl: URL
// let price: Double // let price: Double
enum CodingKeys: String, CodingKey { // enum CodingKeys: String, CodingKey {
case name // case name
case detailText = "description" // case detailText = "description"
} // }
} }
struct DataView: View { struct DataView: View {
@ -28,7 +29,7 @@ struct DataView: View {
private let url = URL(string: "http://127.0.0.1:8080/menu")! private let url = URL(string: "http://127.0.0.1:8080/menu")!
private let jsonDecoder = JSONDecoder() private let jsonDecoder = JSONDecoder()
@State private var menu = MenuCard(items: []) @State private var menu = MenuCard(items: [])
var body: some View { var body: some View {
Text(url.absoluteString) Text(url.absoluteString)
.onAppear{ .onAppear{
@ -42,15 +43,25 @@ struct DataView: View {
) else { return } ) else { return }
if let response = response as? HTTPURLResponse, response.statusCode == 200 { if let response = response as? HTTPURLResponse, response.statusCode == 200 {
menu = try! JSONDecoder().decode(MenuCard.self, from: data) jsonDecoder.keyDecodingStrategy = .convertFromSnakeCase
menu = try! jsonDecoder.decode(MenuCard.self, from: data)
} }
print("fertig geladen") print("fertig geladen")
print(string) print(string)
} }
} }
Text("asdlfaksdf")
ForEach(menu.items, id: \.name) { item in
HStack {
AsyncImage(url: item.imageUrl, scale: 12)
// Text(item.imageUrl.absoluteString )
Text(item.description )
}
}
} }
} }

View file

@ -20,10 +20,6 @@
"comment" : "The title of a section that displays information about the API.", "comment" : "The title of a section that displays information about the API.",
"isCommentAutoGenerated" : true "isCommentAutoGenerated" : true
}, },
"asdlfaksdf" : {
"comment" : "A placeholder text.",
"isCommentAutoGenerated" : true
},
"Betrag" : { "Betrag" : {
"comment" : "A text field for entering an amount.", "comment" : "A text field for entering an amount.",
"isCommentAutoGenerated" : true "isCommentAutoGenerated" : true