UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Trying to capture the JSON from stories

Forums > Swift

{ "stories": [ { "id": "172", "event": "Floyd Lippencotte Interviews" }, { "id": "162", "event": "Florida" }, { "id": "161", "event": "Canyon Lands" } ] }

Can someone tell me what I am doing wrong please in order to capture the data from, "stories"

struct Story: Decodable, Identifiable { public var id: Int public var event: String

enum CodingKeys: String, CodingKey {
       case id = "id"
       case event = "event"

    }

}

public class StoryFetcher: ObservableObject { @Published var stories = [Story]()

init(){
    load()
}

func load() {

    let url = URL(string: "https://logger.lumberjacksystem.com/index.php/api/stories_keywords/74/74")!

    URLSession.shared.dataTask(with: url) {(data,response,error) in
        do {
            if let d = data {
                let decodedLists = try JSONDecoder().decode([Story].self, from: d)
                DispatchQueue.main.async {
                    self.stories = decodedLists
                    print(self.stories)

                }
            }else {
                print("No Data")
            }
        } catch {
            print ("Error")
        }

    }.resume()

}

}

2      

The json you have is not an array of stories but rather JSON object (similar to Swift dictionary), that has stories key and its value is [Story].

In cases like these I would define struct purely for the JSON response. So something like:

struct StoriesResponse: Decodable {
  let stories: [Story]
  }

2      

Thank you very much for your reply. I am DEEPLY GRATEFUL FOR Replying. I just found this video

https://www.hackingwithswift.com/plus/working-with-data/parsing-difficult-json

I will hunt for more of his videos on JSON.

Sincerley, Robert

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.