Home > front end >  How to decode nested Json with Swift?
How to decode nested Json with Swift?

Time:11-26

I have been trying to decode this Json data but I'm not able to do it completly : This is my sample json data :

{
  "id": 10644,
  "name": "CP2500",
  "numberOfConnectors": 2,
  "connectors": [
    {
      "id": 59985,
      "name": "CP2500 - 1",
      "maxchspeed": 22.08,
      "connector": 1,
      "description": "AVAILABLE"
    },
    {
      "id": 59986,
      "name": "CP2500 - 2",
      "maxchspeed": 22.08,
      "connector": 2,
      "description": "AVAILABLE"
    }
  ]
}

this is my struct : `

struct Root: Codable {
    var id: Int
    var name: String
    var numberOfConnectors: Int
    var connectors: [Connector]
}


struct Connector: Codable {
    var id: Int
    var name: String
    var maxchspeed: Double
    var connector: Int
    var connectorDescription: String

    enum CodingKeys: String, CodingKey {
        case id, name, maxchspeed, connector
        case connectorDescription = "description"
    }
}

I want to parse the element within the [Connector] array but I'm just getting the elements of the Root level :

let jsonData = array.data(using: .utf8)!
let root = try JSONDecoder().decode(Root.self, from: jsonData)
print("\(root.id)")

Any idea how to do this ?

CodePudding user response:

do {
    let root = try JSONDecoder().decode(Root.self, from: jsonData)
    print("root id : \(root.id)")
    root.connectors.forEach {
        print("name : \($0.name),"," connector id : \($0.id),","status : \($0.description)");
    }
    
} catch {
    print(error.localizedDescription)
}
  • Related