yanamstyle yanamstyle - 7 months ago 9
Swift Question

how to parse this kind of JSON API by using SwiftyJSON

A project using Swift and parse a JSON API by using a library called SwiftyJSON

[{"A":1,
"B":"2",
"C":"3",
"D":"4"
},
{"A2":12,
"B3":"23",
"C4":"34",
"D5":"45"
}]

↑This is the API and This is the code↓

import UIKit
import SwiftyJSON

class ViewController: UIViewController{


override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

parseJSON()
}

func parseJSON(){

let path:String=NSBundle.mainBundle().pathForResource("jsonFile", ofType: "json")as String!
let jsonData=NSData(contentsOfFile: path) as NSData!
let readableJSON=JSON(data:jsonData, options:NSJSONReadingOptions.MutableContainers, error:nil)

var number=readableJSON["A"]

NSLog("\(number)")
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

}


Somethings wrong and the API’s method is not a Dictionary.

I have to parse a JSON by anyway i could so can somebody tell me the way to parse a API that it's method is an Array?

If you have any other way or alternative's for this project please teach me.

thanks for your cooperation

Answer

The outer object of the json is an array ( [] -> array, {} -> dictionary). The requested dictionary is the first element of the array.

let path = NSBundle.mainBundle().pathForResource("jsonFile", ofType: "json")!
let jsonData = NSData(contentsOfFile: path)!
let readableJSON = JSON(data:jsonData, options:NSJSONReadingOptions.MutableContainers, error:nil)

if let number = readableJSON[0].dictionary?["A"] {
  println(number)
}