NEW: Learn to build amazing SwiftUI apps for macOS with my new book! >>

SOLVED: Decode Complicated JSON

Forums > Swift

I have this JSON:

{
    "customers": ["Example", "another"],

    "projects": [
        {
            "project_name": "Website",
            "customer": "another",
            "timer_progress": "0:34:23"
        },
        {
            "project_name": "Logo",
            "customer": "another",
            "timer_progress": "0:58:56"
        },
        {
            "project_name": "Big Project",
            "customer": "another",
            "timer_progress": "5:23:56"
        }
    ]
}

I would like to store it in two Arrays like this:

customers = ["Example", "another"]

projects = [ { "project_name": "Website", "customer": "another", "timer_progress": "0:34:23" }, { "project_name": "Logo", "customer": "another", "timer_progress": "0:58:56" }, { "project_name": "Big Project", "customer": "another", "timer_progress": "5:23:56" } ]

How can I do it? I already tried some things but they don´t work

1      

I am working with SwiftUI

1      

I'm a little unclear about projects. Are you wanting to decode that into an array of [String:String] dictionaries or will you be decoding into an array of model objects?

1      

@roosterboy id like to have it like this:

projects = [ { "project_name": "Website", "customer": "another", "timer_progress": "0:34:23" }, { "project_name": "Logo", "customer": "another", "timer_progress": "0:58:56" }, { "project_name": "Big Project", "customer": "another", "timer_progress": "5:23:56" } ]

an array with dicts

1      

Here's one way to do it...

//get your JSON data from wherever
//for this example, I just used a static string
let json = """
{
    "customers": ["Example", "another"],

    "projects": [
        {
            "project_name": "Website",
            "customer": "another",
            "timer_progress": "0:34:23"
        },
        {
            "project_name": "Logo",
            "customer": "another",
            "timer_progress": "0:58:56"
        },
        {
            "project_name": "Big Project",
            "customer": "another",
            "timer_progress": "5:23:56"
        }
    ]
}
"""

//this is how we tell Swift what format our raw JSON is in
struct DecodedJSON: Decodable {
    let customers: [String]
    let projects: [[String:String]]
}

struct ContentView: View {

    @State private var customers: [String] = []
    @State private var projects: [[String:String]] = []

    var body: some View {
        Button("Load JSON") {
            loadJSON()
        }
        //so we can see that the data loads
        .onChange(of: customers) { _ in
            print(customers)
        }
        .onChange(of: projects) { _ in
            print(projects)
        }
    }

    func loadJSON() {
        //depending on where your JSON is coming from,
        //you should do the necessary set up steps
        guard let data = json.data(using: .utf8) else {
            fatalError("Could not convert JSON string to data")
        }

        //here's where the actual decoding happens
        do {
            let decodedJSON = try JSONDecoder().decode(DecodedJSON.self, from: data)
            customers = decodedJSON.customers
            projects = decodedJSON.projects
        }
        catch {
            print(error)
        }
    }
}

1      

ok thanks

i try it tomorrow (europe)

1      

Thank You

It works

1      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Spend less time managing in-app purchase infrastructure so you can focus on building your app. RevenueCat gives everything you need to easily implement, manage, and analyze in-app purchases and subscriptions without managing servers or writing backend code.

Get Started

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

Reply to this topic…

You need to create an account or log in to reply.

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.