简体   繁体   中英

How do I parse an array inside parsed JSON in Swift?

I'm using an API that returns JSON that looks like this

{
   "boards":[
      {
         "attribute":"value1"
      },
      {
         "attribute":"value2"
      },
      {
         "attribute":"value3",
      },
      {
         "attribute":"value4",
      },
      {
         "attribute":"value5",
      },
      {
         "attribute":"value6",
      }
   ]
}

In Swift I use two functions to get and then parse the JSON

func getJSON(urlToRequest: String) -> NSData{
    return NSData(contentsOfURL: NSURL(string: urlToRequest))
}

func parseJSON(inputData: NSData) -> NSDictionary{
    var error: NSError?
    var boardsDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(inputData, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary
    return boardsDictionary
}

and then I call it using

var parsedJSON = parseJSON(getJSON("link-to-API"))

The JSON is parsed fine. When I print out

println(parsedJSON["boards"])

I get all the contents of the array. However I am unable to access each individual index. I'm positive it IS an Array, because ween I do

parsedJSON["boards"].count

the correct length is returned. However if I attempt to access the individual indices by using

parsedJSON["boards"][0]

XCode turns off syntax highlighting and gives me this:

XCode错误

and the code won't compile.

Is this a bug with XCode 6, or am I doing something wrong?

Dictionary access in Swift returns an Optional, so you need to force the value (or use the if let syntax) to use it.

This works: parsedJSON["boards"]![0]

(It probably shouldn't crash Xcode, though)

Take a look here: https://github.com/lingoer/SwiftyJSON

let json = JSONValue(dataFromNetworking)
if let userName = json[0]["user"]["name"].string{
    //Now you got your value
}

You can create a variable

var myBoard: NSArray = parsedJSON["boards"] as! NSArray

and then you can access whatever you have in "boards" like-

println(myBoard[0])

The correct way to deal with this would be to check the return from the dictionary key:

    if let element = parsedJSON["boards"] {
        println(element[0])
    }

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