Home > Enterprise >  How to read a json file in this format of array in swift?
How to read a json file in this format of array in swift?

Time:08-28

How to read this format of json in swift? I don't know how to read, I've tried everything. Can someone help me?

I'm new to programming and I appreciate the help in advance! thanks!

{
"ciclo1" : [
    [
        "Laura", 
        "Pedro", 
        "João",
        "Vinicius"
    ],
    [
        "Carlos", 
        "Maria",
        "Leonardo", 
        "Ana"
    ],
    [
        "Daniela",
        "Marcos",
        "Wesley",
        "Luiza"
    ],
    [
        "Daiane",
        "Felipe",
        "Teodoro",
        "Helena"
    ],
    [
        "Natalia",
        "Beatriz",
        "Eduardo",
        "Caio"
    ]
],
"ciclo2" : [
    [
        "Teodoro",
        "Daiane",
        "Luiza"
    ],
    [
        "Carlos",
        "João",
        "Helena"
    ],
    [
        "Daniela",
        "Pedro",
        "Caio"
    ],
    [
        "Leonardo",
        "Maria",
        "Laura"
    ],
    [
        "Beatriz",
        "Marcos",
        "Vinicius"
    ],
    [
        "Natalia",
        "Felipe",
        "Eduardo"
    ],
    [
        "Ana",
        "Wesley"
    ]
]

}

CodePudding user response:

Use QuickType.io

// This file was generated from JSON Schema using quicktype, do not modify it directly.
// To parse the JSON, add this file to your project and do:
//
//   let equipe = try? newJSONDecoder().decode(Equipe.self, from: jsonData)

import Foundation

// MARK: - Equipe
struct Equipe: Codable {
    let ciclo1: [[String]]
    let ciclo2: [[String]]
}

CodePudding user response:

import Foundation

struct Equipe: Codable, Identifiable {
    enum CodingKeys: CodingKey {
        case ciclo1
        case ciclo2
    }
    
    var id = UUID()
    var ciclo1: [[String]]
    var ciclo2: [[String]]
}

class ReadData: ObservableObject {
    @Published var equipes = [[Equipe]]()
    
    init() {
        loadData()
    }
    
    func loadData() {
        guard let url = Bundle.main.url(forResource: "Contents", withExtension: "json")
        else {
            print("Json file not found!")
            return
        }
        
        let data = try? Data(contentsOf: url)
        let equipes = try? JSONDecoder().decode([[Equipe]].self, from: data!)
        self.equipes = equipes!
    }
}
  • Related