使用 swift 获取 JSON 值

getting JSON values with swift

我有一个 url,我想从中获取一些 json 数据,当我在网页中加载 URL 时,这就是 json 的样子,如何在 swift 中获取这些值?

{
            "name" : "name value"
            "serial_number" : "serial_numbe value"
            "status" : "status value"
            ...
}

这是我目前所做的,但它不起作用。我在 URLSession.shared 调用

时遇到 invalid conversion from throwing function of type... 错误
 let web = URL(string: "192.168.101.1:8080/api")
 let webRequest = URLRequest(url: web!)

URLSession.shared.dataTask(with: webRequest, completionHandler: {(data, response, error) in
 guard let data = data, error == nil else {return}

                do{
                    let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
                    let main = json as? [String : Any] ?? []
                    print(["name"])
                }

            })

你可以试试

let web = URL(string: "192.168.101.1:8080/api")
let webRequest = URLRequest(url: web!)

URLSession.shared.dataTask(with: webRequest, completionHandler: {(data, response, error) in
    guard let data = data, error == nil else {return}

    do{
        let main = try JSONSerialization.jsonObject(with: data) as! [String:Any]
        print(main["name"])

        // or
        let dec = JSONDecoder()
        dec.keyDecodingStrategy =.convertFromSnakeCase
        let res = dec.decode(Root.self, from: data)
    }
    catch {

        print(error)
    }

}).resume()

struct Root: Codable {
    let name, serialNumber, status: String
}

你那里有语法错误。

    guard let web = URL(string: "192.168.101.1:8080/api") else { return }

    URLSession.shared.dataTask(with: web) { (data, response, error) in
        guard error == nil, let data = data else { return }
        do {
            let serializedData = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
            guard let json = serializedData as? [String : Any] else { return }
            print(json["name"])
        } catch {
            debugPrint(error)
        }
    }.resume()