Próbuję przeanalizować lokalny plik JSON, który zawiera 3 słowniki, a każdy ma własną tablicę w Coredata, ale zachowuję następujący błąd:

Could not cast value of type '__NSDictionaryM' (0x7fff86b93f10) to 'NSArray' (0x7fff86b92430).

Używam następującego kodu:

private func preloadData() {
    // Get a reference to User Defaults
    let defaults = UserDefaults.standard
    // Get a reference to the persitent container
    let context = persistentContainer.viewContext
    // Check if this is the first launch
    if defaults.bool(forKey: Constants.PRELOAD_DATA) == false {
        // Parse the Json
        let path = Bundle.main.path(forResource: "JSONProjectFinal", ofType: "json")
        // Check that path isn't nil
        guard path != nil else { return }
        // Create a URL
        let url = URL(fileURLWithPath: path!)
        do {
            // Get the data
            let data = try Data(contentsOf: url)
            // Attempt to parse the Json Array
            let jsonArray = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [[String:Any]]

            // Loop through the Json array
            for d in jsonArray {
                // Create the book objects and populate them
                // Populate the Fantasy books
                let f = Fantasy(context: context)
       = d["name"] as? String
                f.imagename = d["imagename"] as? String
       = d["date"] as? String
                f.summary = d["summary"] as? String
                // Populate the Adventure books
                let a = Adventure(context: context)
       = d["name"] as? String
                a.imagename = d["imagename"] as? String
       = d["date"] as? String
                a.summary = d["summary"] as? String
                // Populate the SciFi books
                let sci = SciFi(context: context)
       = d["name"] as? String
                sci.imagename = d["imagename"] as? String
       = d["date"] as? String
                sci.summary = d["summary"] as? String

        } catch { return }

A oto fragment pliku JSON

    "fantasy": [
            "name": "Fellowship of the Ring",
            "imagename": "lotr",
            "date": "24 July 1964",
            "summary": "The Fellowship of the Ring is the first of three volumes in The Lord of the Rings, an epic set in the fictional world of Middle-earth. The Lord of the Rings is an entity named Sauron, the Dark Lord, who long ago lost the One Ring that contains much of his power. His overriding desire is to reclaim the Ring and use it to enslave all of Middle-earth"
            "name": "Harry Potter and the Deathly Hallows",
            "imagename": "harrypotter",
            "date": "21 July 2007",
            "summary": "Without the guidance and protection of their teachers, Harry, Ron and Hermione set out on a mission to destroy the horcruxes, which are the sources of Voldemort's immortality. Although they must trust each other more than ever, forces of darkness threaten to separate them. Voldemort's Death Eaters have taken control of the Ministry of Magic and Hogwarts, and they are looking for Harry as he and his friends prepare for the final confrontation."

Więc jak mam na to pójść? Czy powinienem to rzucić jako słownik tablic? Jestem dość nowy, aby programowanie ogólnie, więc każda pomoc byłaby bardzo doceniana!

Kroling 23 listopad 2020, 15:49

1 odpowiedź

Najlepsza odpowiedź

Twój root to słownik, a nie ma tablicy

guard let res = try JSONSerialization.jsonObject(with: data, options:[:]) as? [String:Any] ,  
      let jsonArray = res["fantasy"] as? [[String:Any]] else { return }
Sh_Khan 23 listopad 2020, 13:04