How to parse Json object in swift 3

后端 未结 1 1445
醉酒成梦
醉酒成梦 2021-01-28 17:01

Hi my question is related to json object. i have this link \"http://ip-api.com/json\" and this link gives the details of your IP Address. i only need to print IP Address from th

1条回答
  •  借酒劲吻你
    2021-01-28 17:56

    The IP address is the value for key query on the top level of the JSON

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

    In Swift 3 the type of a JSON dictionary is [String:Any]

    PS: You don't need a URL request for this task, pass the URL directly and use the native structs URL (and URLRequest)

    let requestURL = URL(string: "http://ip-api.com/json")!
    ...
    let task = session.dataTask(with: requestURL) {
    

    0 讨论(0)
提交回复
热议问题