-1

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 ?

Stee Ve
  • 3
  • 2
  • try to print `array` and look if it really contains any `Connector` children. – burnsi Nov 23 '22 at 21:46
  • 1
    `let connectors = try JSONDecoder().decode(Root.self, from: jsonData).connectors` – Leo Dabus Nov 23 '22 at 22:01
  • What exactly is your issue, it doesn’t look like a decoding problem to me so is this as implied above simply how to access an array property? – Joakim Danielson Nov 24 '22 at 08:02
  • My issue if that I can't print the var "connectorDescription". For ex, I can't not print("\(root.connectors. connectorDescription)"). – Stee Ve Nov 24 '22 at 09:24
  • 1
    `root.connectors.connectorDescription` doesn't work indeed, because it doesn't make sense. `root.connectors` is a Array of `Connector`, so it doesn't have a property `connectorDescription`. Only the elements of that array which are `Connector` have that property. You need to iterate over the elements of that array. – Larme Nov 24 '22 at 09:38

1 Answers1

0
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)
}
gcharita
  • 7,729
  • 3
  • 20
  • 37
Stee Ve
  • 3
  • 2
  • 1
    Side note: avoid using `print(error.localizedDescription)` for `try`, especially on `JSONDecoder`, as it could skip important info about debugging. Prefer using `print(error)` instead. You can simply see by replacing `var id: Int` with `var id: String`, and you'll see the useful info on the real error. – Larme Nov 24 '22 at 10:30