I am attempting to parse JSON from an API in SwiftUI where the response is not an Array, this seems to be the only way I can find online, from my searches.
An example of the response data is as follows:
{
"BillingAccount": {
"AccountType": "Trial",
"AccountBalance": 999.99,
"TransactionCost": 999.99,
"ExtraInformation": {}
},
"TechnicalSupport": {
"ServerId": "UK1",
"RequestId": "442bbc3766074970bc6ac850dab0e851",
"QueryDurationMs": 27,
"SupportDate": "08/07/2024",
"SupportTime": "10:09:36",
"SupportCode": "442bbc37",
"SupportInformationList": [
"B2B-R2"
]
}
}
My test ContentView looks like this:
struct Response: Codable {
var BillingAccount: BillingAccount
var TechnicalSupport: TechnicalSupport
}
struct BillingAccount: Codable {
var AccountType: String
var AccountBalance: Int
var TransactionCost: Int
}
struct TechnicalSupport: Codable {
var ServerId: String
var RequestId: String
var QueryDuration: Int
var SupportDate: String
var SupportTime: String
var SupportCode: String
var SupportInfo: [String]
}
struct ContentView: View {
@State private var results = Response()
let domain = "https://www.domainName.co"
@State var type: String = "type"
@State var apikey: String = "apiKey"
@State var content: String = "content"
var body: some View {
Text(results.AccountType)
.task {
await loadData()
}
}
func loadData() async {
guard let url = URL(string: "(domainName)/api/datapackage/(type)?v=2&api_nullitems=1&auth_apikey=(apiKey)&key_content=(content) ") else {
print("Invalid URL")
return
}
do {
let (data, _) = try await URLSession.shared.data(from: url)
if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {
results = decodedResponse.Response
}
} catch {
print("Invalid data")
}
}
}
I have followed the various tutorials on Hacking With Swift, and have successfully managed to parse JSON with those examples. One that parses JSON from an iTunes API, another from the White House Petitions. Both return JSONs with data in arrays.
But no matter what I try, I just cannot get the JSON to parse. With the above code I currently get the “Missing argument for parameter ‘from’ in call” for the “@State private var results = Response()” line. As well as the “Value of type ‘Response’ has no member ‘Response'” error on the “results = deocdedRepsonse.Repsonse” line.
Any help with this would be greatly appreciated, as well as any explanation as to why I may be finding this difficult.
P.S. I know the API is returning good data as I have the API connected through RapidAPI.
I’ve searched other stack overflow posts, followed a number of Hacking With Swift tutorials on parsing JSON from APIs. Followed the Apple tutorials on parsing JSON.
I just need to parse this JSON. I just can’t work out how to parse the data when it isn’t an Array.
I’ve tried a number of different approaches and always hit an error that I end up chasing to no success.