如何在Swift 5中从jsonserialization中的对象类型获取数据

时间:2019-07-12 07:41:51

标签: json swift serialization

想通过json序列化forRoot

获取此数据

我尝试过这种方法,但是报错(不允许使用方法){"id":1,"name":"harry"}

let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments)

结果应该是这样的:let task = URLSession.shared.dataTask(with: request) {(data, response, error) in let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) print(json) } task.resume()

1 个答案:

答案 0 :(得分:0)

而不是使用<?php extract($_REQUEST); include('config.php'); $sql=mysql_query("select * from inventory_details where id='$del_image'"); $row=mysql_fetch_array($sql); unlink("../image/product1/$row[product1]"); mysql_query("delete from inventory_details where id='$del_image'"); header("Location:edit_inventory.php?edit=$del_image"); ?> ,请尝试使用 JSONSerialization 使用以下模型解析 JSON响应

型号:

Codable

解析:

struct Response: Decodable {
    let id: Int
    let name: String
}

现在,您可以使用let task = URLSession.shared.dataTask(with: request) {(data, response, error) in if let data = data { do { let response = try JSONDecoder().decode(Response.self, from: data) print(response) } catch { print(error) } } } task.resume() 对象访问response和名称id