如何使用 swift 制作正确的本地 JSON 文件和正确的模型 [英] How to make a correct local JSON file and correct model using swift

查看:34
本文介绍了如何使用 swift 制作正确的本地 JSON 文件和正确的模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,我应该在其中将本地 JSON 文件中的所有数据解析为我的标签、歌曲.有一个 JSON 文件,一个数组,两个数组.例如,我需要使用循环数据"在视图控制器和beatloopsdata"之一中在另一个.当我运行此程序时,出现错误,即数据已损坏.有我的 JSON 文件:

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"
            }
        ]
    }
]

}

我已经创建了一个模型,但不确定一切是否正确.我已经尽力了,但这是我第三次使用本地 JSON 文件:

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
}

解析函数:

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
    }
}

推荐答案

我把json数据放到quicktype中,并在代码中使用了生成的数据结构.所以这是工作代码.你可以告诉你的老师,你自己完成了学校的作业.

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:这是我使用的数据,我将这些数据放入一个名为beatpackdata.json"的文件中;在我的 xcode 项目中.

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"
            }
        ]
    }
]
}

这篇关于如何使用 swift 制作正确的本地 JSON 文件和正确的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆