Swiftyjson bundled file

303 views Asked by At

Ok i have a bundled .json file that I am looking to parse with swifty json. The model I am using in swifty json is a top level object that has an array of objects that each contain values of either strings or ints. I was wondering what code I need to create in order to make this. Anyone help in this matter is appreciated. I am new to coding in general and while I actually understand the sequence of most coding this parse function is a bit difficult for me to really grasp. If someone could make me a example code and explain what each part of it does that would be extremely helpful. Lets say I just want to pull one value out of one of the objects and use put it in an array to display in a uitableview. Hope this was clear and any help would be amazing!

1

There are 1 answers

12
derdida On BEST ANSWER

Ok:

  1. Read out your file

    let path = NSBundle.mainBundle().pathForResource("filename", ofType: "json")
    let jsonData = NSData(contentsOfFile: path!, options: NSDataReadingOptions.DataReadingMappedIfSafe, error: nil)
    
  2. load data to SwiftyJSON

    let json = JSON(data: jsonData)
    
  3. Get the Object you want:

    let name = json["key1"]["key2"].stringValue // get any value
    
  4. Or cast as Array

    if let array = json["key_of_array"].array{
        if let string = array[0].string{
    
        // get the first value of an array as string, if there is another key, use: array[0]["key_of_subelement"].string
    
        }
    }
    

And check out this:

http://www.binpress.com/tutorial/swiftyjson-how-to-handle-json-in-swift/111

Here you find some easy ways to read out all data you need