简体   繁体   中英

I tried to get the 'location' from the below JSON, but it returns response 'nil'

I tried to get the location from the below JSON, but it returns response nil , can you check it once. Below URL gives the response, but I want to display location from below JSON.

let url = URL(string: "http://beta.json-generator.com/api/json/get/4ytNy-Nv7")

let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
    if error != nil
    {
        print ("ERROR")
    }
    else
    {
        if let content = data
        {
            do
            {
                //Array
                let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                print(myJson)
                let val = myJson["Location"] as? NSDictionary
                print("val=\(val)")


            }
            catch
            {

            }
        }
    }
}
task.resume()

Don't use Foundation datatypes, such as NSDictionary , when they have native Swift counterparts. You also need to cast the JSON to an array of dictionaries. However, the problem that actually caused the issue was that Location is a String and not a dictionary.

guard let myJsonArray = try JSONSerialization.jsonObject(with: content) as? [[String:Any]], let myJson = myJsonArray.first else {return}
print(myJson)
let val = myJson["Location"] as? String
print("val=\(val)")

The root object of the JSON is clearly an array of a dictionary not something ( AnyObject ). The value for key Location is in the first object of the array

if let myJson = try JSONSerialization.jsonObject(with: content) as? [[String:Any]], !myJson.isEmpty { // check also that the array is not empty
   print(myJson)
   let val = myJson[0] // get first object of the array
   let location = val["Location"] as? String ?? "n/a"
   print("location = \(location)")
}

You can use the following function to download your data. Further more since your array has only one object, to access multiple locations you can iterate through the array objects

func downloadData(){
    let url = URL(string: "http://beta.json-generator.com/api/json/get/4ytNy-Nv7")

    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
        if error != nil
        {
            print ("ERROR")
        }
        else
        {
            if let content = data
            {
                do
                {
                    let myJson = try JSONSerialization.jsonObject(with: content) as? [[String:Any]]
                    let object = myJson?[0]
                    if let location = object?["Location"] as? String{
                        print(location)
                    }
                }
                catch
                {
                }
            }
        }
    }
    task.resume()
}

You can change this part :

let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject

Into :

let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as! [AnyHashable: Any]

Then if your JSON only have one object try this to get the Location :

let obj = myJson[0]
let location = obj["Location"] as? String
print("Location \(location)")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM