使用SwiftyJson iOS解码嵌套Json,缺少对象

时间:2019-10-16 10:00:25

标签: ios swifty-json codable

我正在调用此api来接收一次火箭发射事件: https://launchlibrary.net/1.4/launch/next/1使用简单的Get请求。 尝试使用SwiftyJson(也尝试Codable)进行解码,但无法成功读取“火箭”->“ imageURL”

这是我的代码:

struct LaunchHistory {
var launches = [LaunchItem]()

init(with json:JSON) {
    for launch in json["launches"].arrayValue {
        let launchItem = LaunchItem(with: launch)
        launches.append(launchItem)
     }
   }
 }


struct LaunchItem {
let id:Int?
let name: String?
let tbddate: Int?
let status: LaunchStatus?
let rocketImage: String?

init(with json:JSON) {
    self.id = json["id"].int
    self.name = json["name"].string
    self.tbddate = json["tbddate"].int
    self.status = LaunchStatus(rawValue: json["status"].int ?? 0)
    self.rocketImage = json["rocket"]["imageURL"].string
    }
}

LaunchItem解码时,所有i 11个属性/键都几乎增加了一倍。 rocket对象丢失。 我在这里想念什么?

谢谢!

1 个答案:

答案 0 :(得分:1)

使用(De)Codable

非常简单
struct Root : Decodable {
    let launches : [LaunchItem]
}

struct LaunchItem : Decodable {
    let id: Int
    let name: String
    let tbddate: Int
    let rocket: Rocket
}

struct Rocket : Decodable {
    let imageURL : URL
}

let url = URL(string: "https://launchlibrary.net/1.4/launch/next/1")!
let task = URLSession.shared.dataTask(with: url) { (data, _, error) in
    if let error = error { print(error); return }
    do {
        let result = try JSONDecoder().decode(Root.self, from: data!)
        print(result.launches.first?.rocket.imageURL ?? "n/a")
    } catch {
        print(error)
    }

}
task.resume()