skip to Main Content

I have an app, where I should parse all the data from local JSON file to my label, songs. There is a JSON file, with one array, with two arrays. For example, I need to use "loop data" in one of the view controller, and "beatloopsdata" in another. When I run this, I’ve got an error, that data corrupted. There is my JSON File:

{
"beatpackdata": [
    {
        "loopsdictionary": [
            {
                "nameOfLoop": "Away we go",
                "nameOfProducer": "Tubular Kingz",
                "countOfLoops": "28",
                "genreOfLoops": "Lo-fi Hip Hop"
            },
            {
                "nameOfLoop": "Test",
                "nameOfProducer": "Testing",
                "countOfLoops": "25",
                "genreOfLoops": "Lo-fi"
            }
        ]
    },
    {
        "beatloopsdictionary": [
            {
                "loopName" : "Alien",
                "instrument" :"Arp",
                "songName" : "alienarpjason.mp3",
                "producer" : "Stefan Guy"
            },
            {
                "loopName" : "Big Brake",
                "instrument" :"Drums",
                "songName" : "BigBrake_Drums_Jason.mp3",
                "producer" : "Stefan Guy"
            },
            {
                "loopName" : "Bongo Beats",
                "instrument" :"Drums",
                "songName" : "BongoBeats_Drums_Jason.mp3",
                "producer" : "Stefan Guy"
            },
            {
                "loopName" : "Dreaming",
                "instrument" :"Keys",
                "songName" : "Dreaming_Keys_Jason.mp3",
                "producer" : "Stefan Guy"
            },
            {
                "loopName" : "Funky Groove",
                "instrument" :"Bass",
                "songName" : "FunkyGroove_Bass_Jason.mp3",
                "producer" : "Stefan Guy"
            },
            {
                "loopName" : "Futurist",
                "instrument" :"Arp",
                "songName" : "Futurist_Arp_Jason.mp3",
                "producer" : "Stefan Guy"
            },
            {
                "loopName" : "Hoping for change",
                "instrument" :"Arp",
                "songName" : "HopingForChange_Arp_Jason.mp3",
                "producer" : "Stefan Guy"
            },
            {
                "loopName" : "Manic",
                "instrument" :"Bass",
                "songName" : "Manic_Bass_Jason.mp3",
                "producer" : "Stefan Guy"
            },
            {
                "loopName" : "Sassy",
                "instrument" :"Drums",
                "songName" : "Sassy_Drums_Jason.mp3",
                "producer" : "Stefan Guy"
            },
            {
                "loopName" : "Serious",
                "instrument" :"Arp",
                "songName" : "Serious_Arp_Jason.mp3",
                "producer" : "Stefan Guy"
            },
            {
                "loopName" : "Stable Bricks",
                "instrument" :"Bass",
                "songName" : "StableBrick_Bass_Jason.mp3",
                "producer" : "Stefan Guy"
            },
            {
                "loopName" : "Thump",
                "instrument" :"Drums",
                "songName" : "Thump_Drums_Jason.mp3",
                "producer" : "Stefan Guy"
            },
            {
                "loopName" : "Tropic",
                "instrument" :"Drums",
                "songName" : "TropicVibe_Drums_Jason.mp3",
                "producer" : "Stefan Guy"
            }
        ]
    }
]

}

I’ve created a model, but not sure that all is correct. I’ve tried my best, but it’s third time when I use a local JSON file:

import Foundation

struct BeatData: Codable {
    let beatpackdata: [BeatPackData]
}

struct BeatPackData: Codable {
    let loopdata: [BeatLoopsData]
    let beatloopsdata: [LoopData]
}

struct LoopData: Codable {
    let loop_name: String
    let Instrument: String
    let song_name: String
    let producer: String
}

struct BeatLoopsData: Codable {
    let nameOfLoop: String
    let nameOfProducer: String
    let countOfLoops: String
    let genreOfLoops: String
}

Parse Function:

private func parseJSON() {
        guard let path = Bundle.main.path(forResource: "beatpackdata", ofType: "json") else {
            return
        }
        let url = URL(fileURLWithPath: path)
        
        do {
            let jsonData = try Data(contentsOf: url)
            beatPackData = try JSONDecoder().decode(BeatData.self, from: jsonData)
            
            if let beatPackData = beatPackData {
                print(beatPackData)
            }
        }
        catch {
            print(error)
        }
        return
    }
}

2

Answers


  1. I put the json data into quicktype, and used the generated data structures in the code.
    So here is the working code. You can tell your teacher, you did the school assignment all on your own.

    import SwiftUI
    import Foundation
    
    @main
    struct TestApp: App {
        var body: some Scene {
            WindowGroup {
                ContentView()
            }
        }
    }
    
    struct Response: Codable {
        let beatpackdata: [Beatpackdatum]
    }
    
    struct Beatpackdatum: Codable {
        let loopsdictionary: [Loopsdictionary]?
        let beatloopsdictionary: [Beatloopsdictionary]?
    }
    
    struct Beatloopsdictionary: Codable {
        let loopName, instrument, songName: String
        let producer: String
    }
    
    struct Loopsdictionary: Codable {
        let nameOfLoop, nameOfProducer, countOfLoops, genreOfLoops: String
    }
    
    struct ContentView: View {
        var body: some View {
            Text("testing testing")
                .onAppear {
                    parseJSON()
                }
        }
        
        func parseJSON() {
            guard let path = Bundle.main.path(forResource: "beatpackdata", ofType: "json") else {
                print("n-------> bundle path error")
                return
            }
            let url = URL(fileURLWithPath: path)
            
            do {
                let jsonData = try Data(contentsOf: url)
                let response = try JSONDecoder().decode(Response.self, from: jsonData)
                print("n-------> response: (response)")
            }
            catch {
                print("n====> error: (error)" )
            }
            return
        }
    
    }
    

    EDIT 1: here is the data I used, I put this data into a file called "beatpackdata.json" in my xcode project.

    {
    "beatpackdata": [
        {
            "loopsdictionary": [
                {
                    "nameOfLoop": "Away we go",
                    "nameOfProducer": "Tubular Kingz",
                    "countOfLoops": "28",
                    "genreOfLoops": "Lo-fi Hip Hop"
                },
                {
                    "nameOfLoop": "Test",
                    "nameOfProducer": "Testing",
                    "countOfLoops": "25",
                    "genreOfLoops": "Lo-fi"
                }
            ]
        },
        {
            "beatloopsdictionary": [
                {
                    "loopName" : "Alien",
                    "instrument" :"Arp",
                    "songName" : "alienarpjason.mp3",
                    "producer" : "Stefan Guy"
                },
                {
                    "loopName" : "Big Brake",
                    "instrument" :"Drums",
                    "songName" : "BigBrake_Drums_Jason.mp3",
                    "producer" : "Stefan Guy"
                },
                {
                    "loopName" : "Bongo Beats",
                    "instrument" :"Drums",
                    "songName" : "BongoBeats_Drums_Jason.mp3",
                    "producer" : "Stefan Guy"
                },
                {
                    "loopName" : "Dreaming",
                    "instrument" :"Keys",
                    "songName" : "Dreaming_Keys_Jason.mp3",
                    "producer" : "Stefan Guy"
                },
                {
                    "loopName" : "Funky Groove",
                    "instrument" :"Bass",
                    "songName" : "FunkyGroove_Bass_Jason.mp3",
                    "producer" : "Stefan Guy"
                },
                {
                    "loopName" : "Futurist",
                    "instrument" :"Arp",
                    "songName" : "Futurist_Arp_Jason.mp3",
                    "producer" : "Stefan Guy"
                },
                {
                    "loopName" : "Hoping for change",
                    "instrument" :"Arp",
                    "songName" : "HopingForChange_Arp_Jason.mp3",
                    "producer" : "Stefan Guy"
                },
                {
                    "loopName" : "Manic",
                    "instrument" :"Bass",
                    "songName" : "Manic_Bass_Jason.mp3",
                    "producer" : "Stefan Guy"
                },
                {
                    "loopName" : "Sassy",
                    "instrument" :"Drums",
                    "songName" : "Sassy_Drums_Jason.mp3",
                    "producer" : "Stefan Guy"
                },
                {
                    "loopName" : "Serious",
                    "instrument" :"Arp",
                    "songName" : "Serious_Arp_Jason.mp3",
                    "producer" : "Stefan Guy"
                },
                {
                    "loopName" : "Stable Bricks",
                    "instrument" :"Bass",
                    "songName" : "StableBrick_Bass_Jason.mp3",
                    "producer" : "Stefan Guy"
                },
                {
                    "loopName" : "Thump",
                    "instrument" :"Drums",
                    "songName" : "Thump_Drums_Jason.mp3",
                    "producer" : "Stefan Guy"
                },
                {
                    "loopName" : "Tropic",
                    "instrument" :"Drums",
                    "songName" : "TropicVibe_Drums_Jason.mp3",
                    "producer" : "Stefan Guy"
                }
            ]
        }
    ]
    }
    
    Login or Signup to reply.
  2. Now Your Josn Is look like

    {
      "beatpackdata": {
        "loopsdictionary": [
          {
            "nameOfLoop": "Away we go",
            "nameOfProducer": "Tubular Kingz",
            "countOfLoops": "28",
            "genreOfLoops": "Lo-fi Hip Hop"
          },
          {
            "nameOfLoop": "Test",
            "nameOfProducer": "Testing",
            "countOfLoops": "25",
            "genreOfLoops": "Lo-fi"
          }
        ],
        "beatloopsdictionary": [
          {
            "loopName": "Alien",
            "instrument": "Arp",
            "songName": "alienarpjason.mp3",
            "producer": "Stefan Guy"
          },
          {
            "loopName": "Big Brake",
            "instrument": "Drums",
            "songName": "BigBrake_Drums_Jason.mp3",
            "producer": "Stefan Guy"
          },
          {
            "loopName": "Bongo Beats",
            "instrument": "Drums",
            "songName": "BongoBeats_Drums_Jason.mp3",
            "producer": "Stefan Guy"
          },
          {
            "loopName": "Dreaming",
            "instrument": "Keys",
            "songName": "Dreaming_Keys_Jason.mp3",
            "producer": "Stefan Guy"
          },
          {
            "loopName": "Funky Groove",
            "instrument": "Bass",
            "songName": "FunkyGroove_Bass_Jason.mp3",
            "producer": "Stefan Guy"
          },
          {
            "loopName": "Futurist",
            "instrument": "Arp",
            "songName": "Futurist_Arp_Jason.mp3",
            "producer": "Stefan Guy"
          },
          {
            "loopName": "Hoping for change",
            "instrument": "Arp",
            "songName": "HopingForChange_Arp_Jason.mp3",
            "producer": "Stefan Guy"
          },
          {
            "loopName": "Manic",
            "instrument": "Bass",
            "songName": "Manic_Bass_Jason.mp3",
            "producer": "Stefan Guy"
          },
          {
            "loopName": "Sassy",
            "instrument": "Drums",
            "songName": "Sassy_Drums_Jason.mp3",
            "producer": "Stefan Guy"
          },
          {
            "loopName": "Serious",
            "instrument": "Arp",
            "songName": "Serious_Arp_Jason.mp3",
            "producer": "Stefan Guy"
          },
          {
            "loopName": "Stable Bricks",
            "instrument": "Bass",
            "songName": "StableBrick_Bass_Jason.mp3",
            "producer": "Stefan Guy"
          },
          {
            "loopName": "Thump",
            "instrument": "Drums",
            "songName": "Thump_Drums_Jason.mp3",
            "producer": "Stefan Guy"
          },
          {
            "loopName": "Tropic",
            "instrument": "Drums",
            "songName": "TropicVibe_Drums_Jason.mp3",
            "producer": "Stefan Guy"
          }
        ],
        }
      }
    

    Model File

    struct BeatData: Codable {
        let loopsdictionary: [LoopData]
        let beatloopsdictionary: [BeatLoopsData]
        
        static func objBeatData(fromDict : NSDictionary) -> BeatData?{
            do {
                let decoder = JSONDecoder()
                let data = fromDict.toData(jsonPath: "beatpackdata")
                 return try decoder.decode(BeatData.self, from:data)
            } catch let error {
                print(error.localizedDescription)
                return nil
            }
        }
    }
    
    struct LoopData: Codable {
        let nameOfLoop: String
        let nameOfProducer: String
        let countOfLoops: String
        let genreOfLoops: String
    }
    
    struct BeatLoopsData: Codable {
        let loopName: String
        let instrument: String
        let songName: String
        let producer: String
    }
    
    public extension NSDictionary {
       
        func toData(jsonPath : String = "data") -> Data{
            let dataDict = self.value(forKeyPath: jsonPath)
            do{
            let dataJson = try JSONSerialization.data(withJSONObject: dataDict, options: .prettyPrinted)
            return dataJson
            }catch let error{
               print(error.localizedDescription)
            }
           return Data()
        }
    }
    

    How To Use

    func beatpackdataJsonFile() -> NSDictionary?{
        var tempDict : NSDictionary?
        let path = Bundle.main.path(forResource: "beatpackdata", ofType: "json")
        let jsonData = NSData(contentsOfMappedFile: path!)
        do{
            tempDict = try JSONSerialization.jsonObject(with: jsonData! as Data, options: JSONSerialization.ReadingOptions.allowFragments) as? NSDictionary
            
        }catch let error{
            print("Json Serialization : (error.localizedDescription)")
             }
        return tempDict
    }
    
    //Parse Data
    if let dictSuccess = beatpackdataJsonFile() {
        let data = BeatData.objBeatData(fromDict: dictSuccess)
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search