Home > Software design >  Json decode result is printing into console in swift playground
Json decode result is printing into console in swift playground

Time:11-21

I am new to swift . I created simple playground and added the file with extension json into playground . I am trying to decode the result and print the ID into console but any reason ,it not printing the result into console , I do not see error into console window ..

Here is the playground project structure .. enter image description here

Here is my json file ..

let json = """
{
 "id": "1",
 "options": [
 {
 "id": "11",
 "options": [
 {
 "id": "111",
 "options": []
 }
 ]
 },
 {
 "id": "2",
 "options": [
 {
 "id": "21",
 "options": []
 },
 {
 "id": "22",
 "options": [
 {
 "id": "221",
 "options": []
 }
 ]
 }
 ]
 }
 ]
}

Here is the code .. I tried ..

struct People: Codable {
    let id: String
    let options: [People]
}
func loadJson(filename fileName: String) -> People? {
    if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
        do {
            let data = try Data(contentsOf: url)
            let decoder = JSONDecoder()
            let jsonData = try decoder.decode(People.self, from: data)
            print(jsonData.id)
            return jsonData
        } catch {
            print("error:\(error)")
        }
    }
    return nil
}

It not printing the ID of the decode json ..

CodePudding user response:

So I did get it to print the ID, I changed the people file name to people.json and changed the contents to:

{
    "id": "1",
    "options": [{
            "id": "11",
            "options": [{
                "id": "111",
                "options": []
            }]
        },
        {
            "id": "2",
            "options": [{
                    "id": "21",
                    "options": []
                },
                {
                    "id": "22",
                    "options": [{
                        "id": "221",
                        "options": []
                    }]
                }
            ]
        }
    ]
}

(Notice I removed the let json = statement.)

After that in the playground where define the People struct and the loadJson method you can call it like so:

loadJson(filename: "people")

So now you end up with:

struct People: Codable {
    let id: String
    let options: [People]
}


func loadJson(filename fileName: String) -> People? {
    if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
        do {
            let data = try Data(contentsOf: url)
            let decoder = JSONDecoder()
            let jsonData = try decoder.decode(People.self, from: data)
            print(jsonData.id)
            return jsonData
        } catch {
            print("error:\(error)")
        }
    }
    return nil
}

loadJson(filename: "people")
  • Related