使用以下代码,我可以有效地获取JSON对象,但不确定如何从对象中检索特定属性。
@IBAction func testing(_ sender: Any) {
let url = URL(string: "http://example.com/cars/mustang")
let task = URLSession.shared.dataTask(with: url!) { data, response, error in
guard error == nil else {
print(error!)
return
}
guard let data = data else {
print("Data is empty")
return
}
let json = try! JSONSerialization.jsonObject(with: data, options: [])
print(json)
}
task.resume()
}
当我运行上面的代码时,这就是我看到的...
(
{
color = "red";
engine = "5.0";
}
)
如何仅获取属性颜色?
谢谢
答案 0 :(得分:2)
创建一个确认可解码协议的类;以您的情况为例的CarInfo
class CarInfo: Decodable
创建类的属性
var color: String
var engine: String
创建从CodingKey继承的JSON密钥枚举
enum CarInfoCodingKey: String, CodingKey {
case color
case engine
}
实现初始化
required init(from decoder: Decoder) throws
班级将是
class CarInfo: Decodable {
var color: String
var engine: String
enum CarInfoCodingKey: String, CodingKey {
case color
case engine
}
public init(from decoder: Decodabler) throws {
let container = try decoder.container(keyedBy: CarInfoCodingKey.self)
self.color = try container.decode(String.self, forKey: .color)
self.engine = try contaire.decode(String.self, forKey: .engine)
}
}
通话解码器
let carinfo = try JsonDecoder().decode(CarInfo.self, from: jsonData)
答案 1 :(得分:0)
这是我的方法...
@IBAction func testing(_ sender: Any) {
let url = URL(string: "http://example.com/cars/mustang")
let task = URLSession.shared.dataTask(with: url!) { data, response, error in
guard error == nil else {
print(error!)
return
}
guard let data = data else {
print("Data is empty")
return
}
let json = try! JSONSerialization.jsonObject(with: data, options: [])
guard let jsonArray = json as? [[String: String]] else {
return
}
let mustangColor = jsonArray[0]["color"]
print(mustangColor!)
}
task.resume()
}