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

前端 未结 4 684
后悔当初
后悔当初 2020-12-08 10:32

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

{
   \"boards\":[
      {
         \"attribute\":\"value1\"
      },
      {
         \"attribute\":         


        
相关标签:
4条回答
  • 2020-12-08 10:43

    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
    }
    
    0 讨论(0)
  • 2020-12-08 10:50

    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)

    0 讨论(0)
  • 2020-12-08 10:57

    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])
    
    0 讨论(0)
  • 2020-12-08 10:57

    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])
        }
    
    0 讨论(0)
提交回复
热议问题