How to loop through JSON with SwiftyJSON?

后端 未结 5 1976
一向
一向 2020-12-13 08:59

I have a json that I could parse with SwiftyJSON :

if let title = json[\"items\"][2][\"title\"].string {
     println(\"title : \\(title)\")
}
5条回答
  •  星月不相逢
    2020-12-13 10:03

    I Find it a bit strange explained myself, because actually using:

    for (key: String, subJson: JSON) in json {
       //Do something you want
    }
    

    gives syntax errors (in Swift 2.0 atleast)

    correct was:

    for (key, subJson) in json {
    //Do something you want
    }
    

    Where indeed key is a string and subJson is a JSON object.

    However I like to do it a little bit different, here is an example:

    //jsonResult from API request,JSON result from Alamofire
       if let jsonArray = jsonResult?.array
        {
            //it is an array, each array contains a dictionary
            for item in jsonArray
            {
                if let jsonDict = item.dictionary //jsonDict : [String : JSON]?
                {
                    //loop through all objects in this jsonDictionary
                    let postId = jsonDict!["postId"]!.intValue
                    let text = jsonDict!["text"]!.stringValue
                    //...etc. ...create post object..etc.
                    if(post != nil)
                    {
                        posts.append(post!)
                    }
                }
            }
       }
    

提交回复
热议问题