如何在swift中显示json-out中的每个对象



目前我能够显示返回json数据的full-out from GET方法。

但我无法展示单个物体。即描述或引擎的值。但是我可以打印整个json数据。我的代码

let url = URL(string: "https://mylink/last")!
var request = URLRequest(url: url)
request.allHTTPHeaderFields = [
"Content-Type": "application/json",
"Session": "b14549"
]

let session =  URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print (response)
}
if let data = data {
print (data)
do {
let jsonresult = try JSONSerialization.jsonObject(with: data, options: [])
// This works
print (jsonresult)
// Bellow does not work , Give Error Value of type 'any' has no subscripts
print (jsonresult["device_id"])
print (jsonresult["engine"])

} catch {
print(error)
}

}
}.resume()
}

我查看了其他解决方案,尝试了以下不起作用,不确定它是否与我获得的数据类型有关。我已经发布了jsonresult的输出如下。

JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String: Any]

Json结果的输出:-

(
{
"device_id" = "3aff273f-7f5f-49ef-81a6-50e2fcc2f69f”;
engine = 0;
"last_timestamp" = "2019-10-25 17:33:45";

},
{
"device_id" = "44b0ab5f-5289-4c56-b864-ce4899c2fcb8”;
engine = 0;
"last_timestamp" = "2019-10-25 17:33:40";
},
{
"device_id" = "c5639e8b-7f56-4021-9925-828ed735f527";
engine = 0;

}
)
  1. 结果显然是一个数组,请注意输出中的()
  2. 您必须将结果强制转换为预期类型

    if let jsonresult = try JSONSerialization.jsonObject(with: data) as? [[String:Any]] {
    for item in jsonresult {
    print(item["device_id"])
    print(item["engine"])
    }
    }
    

最新更新