简体   繁体   中英

Swift JSON Parsing to dictionary

I'm having trouble accessing/printing some nested JSON data. The code below works when I use commented print(json) to print the entire array, but when I try to step inside the the objects it gives an error. I think it's because instead of a straight array the structure is a little different. JSON data is nested in a dictionary called "data"

Would love some help trying to print the "title" fields as an example. Thanks a lot.

func fetchTvItems()   {

    let url = NSURL(string: "hidden")

    URLSession.shared.dataTask(with: url! as URL) { (data, response, error) in

        if error != nil {
            print(error ?? "URLSession error")
            return
        }

        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)

            for dictionary in json as! [[String: AnyObject]]    {
                print(dictionary["title"]!)
            }
            //print(json)

        } catch let jsonError {
            print(jsonError)
        }

    }.resume()

You are stating wrong things here.

First thing you are storing json data in Array. But it's inside Dictionary keyed "data"

so, first try to store dictionary to array. Try below code

if let arry = json["data"] as? [[String:AnyObject]] {
         for dictionary in arry {
                print(dictionary["title"]!)
            }  
}

First of all a JSON dictionary in Swift 3+ is [String:Any] rather than [String:AnyObject] .

  • The root object is a dictionary ( [String:Any] ).
  • The value for key data is an array of dictionaries ( [[String:Any]] ).

Please read the JSON. It's very easy. {} is dictionary, [] is array.

The option .mutableContainers is completely useless in Swift.

    do {
        if let json = try JSONSerialization.jsonObject(with: data!) as? [String:Any],
           let data = json["data"] as? [[String:Any]] {

              for dictionary in data {
                  print(dictionary["title"] as? String ?? "n/a")
              }
           }
    } catch {
        print(error)
    }

Hope help you

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

is String data root. You must access to key "data" string json.

let array = json["data"] as? [[String:AnyObject]

Now you can use array and for data you want.

Good luck.

This is testet with your code

let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String: AnyObject]

for item in json["data"] as! [[String: AnyObject]] {
     print(item["title"] as! String)
}

Swift 4

With JSONSerialization it can be done easily.

func convertToDictionary(text: String) -> [String: Any]? {
    if let data = text.data(using: .utf8) {
        do {
            return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
        } catch {
            // Handle Error
        }
    }
    return nil
}

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