{
"data":{
"email":"[email protected]",
"password":"123",
"token":""
}
}
struct JsonResult: View{
@State private var results = [GetData]()
var body: some View{
List(results, id: .email){ item in
VStack(alignment: .leading) {
Text(item.password)
.font(.headline)
Text(item.token)
.font(.headline)
}
}.task {
await loadData()
}
}
struct Response : Codable {
var results: [GetData]
}
struct GetData: Codable{
var data : [Result]
}
struct Result: Codable {
var email: String
var password: String
var token: String
}
func loadData() async{
guard let url = URL(string: "MYURL") else {
print("invalid URL")
return
}
do{
let(data,_) = try await URLSession.shared.data(from: url)
// more code
if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data)
{
results = decodedResponse.results
}
} catch {
print("Invalid Data")
}
}
}
i need to know if the codable structure is right according to the structure of data i gave ? and also the fetching in list ? please i need help in the URLsession i am still new and i barely know about url alot !
i would be grateful if you help me ! thank you verrrry much !!!!
2
Answers
In the JSON there is no array involved (no
[]
at all).The model corresponding to the JSON is
So the data source cannot be declared as an array. To avoid an optional type create an enum with associated values indicating a state. The benefit is that you can show different views depending on the state
this is the rest of the struct, consider that there is no
List
either becauseUserData
is a single object.