How to parse JSON from an API in SwiftUI, where the response is not an Array, asynchronously?

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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>{
"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"
]
}
}
</code>
<code>{ "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" ] } } </code>
{
  "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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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")
}
}
}
</code>
<code>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") } } } </code>
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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật