如何用Swift解码嵌套的Json?

8mmmxcuj  于 2022-11-26  发布在  Swift
关注(0)|答案(1)|浏览(187)

我一直在尝试解码此Json数据,但无法完全解码:这是我的示例json数据:

{
  "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"
    }
  ]
}

这是我结构体:`

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"
    }
}

我想解析[Connector]数组中的元素,但我只是获取根级别的元素:

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

知道怎么做吗?

qxsslcnc

qxsslcnc1#

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)
}

相关问题