快速获取JSON值

时间:2019-07-11 14:20:14

标签: ios json swift webrequest

我有一个要从中获取一些json数据的URL,当我将URL加载到网页中时,这就是json的样子,如何快速获取这些值?

{
            "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"])
                }

            })

2 个答案:

答案 0 :(得分:0)

您可以尝试

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
}

答案 1 :(得分:0)

其中存在语法错误。

    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()