2021年3月12日星期五

Fetch data from nested JSON API in SwiftUI (object in array in object in another object)

Beginner here, in a bit over my head with this. ;)

I've found examples that have shown me how to get data from a JSON API feed if the feed is structured as an array of objects, but I don't know how to approach getting the data (specifically, url and title) if the data I'm retrieving comes back in a more complex nested structure like this one:

{      "races": {          "videos": [{              "id": 1,              "url": "firsturl",              "title": "1st Video Title"          }, {              "id": 2,              "url": "secondurl",              "title": "2nd Video Title"          }]      }  }  

I've succeeded at get data from another API feed that's structured as a simple array of objects--it's like what's above but without the extra two lead-in objects, namely this: { "races": { "videos":

Here's the code I pieced together from a few examples that worked for the simple array:

import SwiftUI    struct Video: Codable, Identifiable {      public var id: Int      public var url: String      public var title: String  }    class Videos: ObservableObject {    @Published var videos = [Video]()             init() {          let url = URL(string: "https://exampledomain.com/jsonapi")!          URLSession.shared.dataTask(with: url) {(data, response, error) in              do {                  if let videoData = data {                      let decodedData = try JSONDecoder().decode([Video].self, from: videoData)                      DispatchQueue.main.async {                          self.videos = decodedData                      }                  } else {                      print("no data found")                  }              } catch {                  print("an error occurred")              }          }.resume()      }  }    struct VideosView: View {      @ObservedObject var fetch = Videos()      var body: some View {          VStack {              List(fetch.videos) { video in                  VStack(alignment: .leading) {                      Text(video.title)                      Text("\(video.url)")                  }              }          }      }  }  

I've spent several hours over a few days reading and watching tutorials, but so far nothing is sinking in to help me tackle the more complex JSON API feed. Any tips would be greatly appreciated!

https://stackoverflow.com/questions/66609795/fetch-data-from-nested-json-api-in-swiftui-object-in-array-in-object-in-another March 13, 2021 at 11:17AM

没有评论:

发表评论