简体   繁体   中英

Parsing objects in Json array as a dictionary Swift

So I have JSON data that is formatted as a list of dictionaries, and I have it stored as an NSArray Object, but I'm unsure how to convert each entry into a dictionary object when it is currently AnyObject

The AnyObject data is already formatted like a JSON dictionary

Here is the code I used to create the Array

func startConnection(){
    let urlPath: String = "http://api.mtgdb.info/search/omni"
    var url: NSURL = NSURL(string: urlPath)!
    var request: NSURLRequest = NSURLRequest(URL: url)
    var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
    connection.start()




}

func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
    self.data.appendData(data)
}

func connectionDidFinishLoading(connection: NSURLConnection!){
    var err: NSError
    var jsonResult: NSArray = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSArray
    for var i = 0; i<jsonResult.count; ++i{
       ...

    }

}

I tried this sample code to solve your problem. First of all run this " http://api.mtgdb.info/search/omni " URL in web browser and copy response then paste into " http://jsonlint.com ", response is valid and I get array of 8 dictionaries, Like id: 37113, 39932, 83737, 106426, 228247, 288937, 382286, 386302 -- 8 data.

In Objective C, It works perfect and I get same result as web browser. But in Swift, It behave weird, Can't parse whole respose, get only half dictionary as object of array. Only get this much part of response,

Printing description of jsonResult: ( { artist = "Arnie Swekel"; cardSetId = JUD; cardSetName = Judgment; colors = ( green, white ); convertedManaCost = 7; description = "Trample\\nPhantom Nishoba enters the battlefield with seven +1/+1 counters on it.\\nWhenever Phantom Nishoba deals damage, you gain that much life.\\nIf damage would be dealt to Phantom Nishoba, prevent that damage. Remove a +1/+1 counter from Phantom Nishoba."; flavor = ""; formats = ( { legality = Legal; name = "Odyssey Block"; }, { legality = Legal; name = Legacy; }, { legality = Legal; name = Vintage; }, { legality = Legal; name = Freeform; }, { legal

I tried this sample of code

class ViewController: UIViewController, NSURLConnectionDelegate {

var data:NSMutableData!
var arrvehicls:NSMutableArray!


override func viewDidLoad() {
    super.viewDidLoad()
    self.data = NSMutableData()
    self.arrvehicls = NSMutableArray()

    self.startConnection()
}

func startConnection(){
    let urlPath: String = "http://api.mtgdb.info/search/omni"
    var url: NSURL = NSURL(string: urlPath)!
    var request: NSURLRequest = NSURLRequest(URL: url)
    var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
    connection.start()
}

func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
    self.data.appendData(data)
}

func connectionDidFinishLoading(connection: NSURLConnection!) {

    var err: NSError
    var jsonResult:NSArray = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSArray

    for var i = 0; i<jsonResult.count; ++i {

        var dictResult = jsonResult.objectAtIndex(i) as! NSDictionary

        var vehicleInfo = Vehicle()
        vehicleInfo.id = dictResult.valueForKey("id") as! Int
        vehicleInfo.artist = dictResult.valueForKey("artist") as! String
        vehicleInfo.cardID = dictResult.valueForKey("cardSetId") as! String
        vehicleInfo.cardName = dictResult.valueForKey("cardSetName") as! String
        vehicleInfo.colors = dictResult.valueForKey("colors") as! NSArray
        vehicleInfo.details = dictResult.valueForKey("description") as! String
        vehicleInfo.flavour = dictResult.valueForKey("flavor") as! String
        vehicleInfo.formats = NSMutableArray()
        var arr = dictResult.valueForKey("formats") as! NSArray

        for var j = 0; j<arr.count; ++i {

            var dictFormats = arr.objectAtIndex(i) as! NSDictionary
            var formats = Formats()
            formats.legality = dictFormats.valueForKey("legality") as! String
            formats.name = dictFormats.valueForKey("name") as! String
            vehicleInfo.formats.addObject(formats)
        }
        self.arrvehicls.addObject(vehicleInfo)
    }
}
}

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