Ios: JSONobjectwithdata

How to use NSJSONSerialization

Your root json object is not a dictionary but an array:

[{"id": "1", "name":"Aaa"}, {"id": "2", "name":"Bbb"}]

This might give you a clear picture of how to handle it:

NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];

if (!jsonArray) {
NSLog(@"Error parsing JSON: %@", e);
} else {
for(NSDictionary *item in jsonArray) {
NSLog(@"Item: %@", item);
}
}

Swift 2 - NSJSONSerialization.JSONObjectWithData Handling Error

swift3

NSJSONSerialization and its methods are modified, according to the Swift Documents.

do {

let JsonDict = try JSONSerialization.jsonObject(with: data, options: [])
// you can now use t with the right type
if let dictFromJSON = JsonDict as? [String:String]
{
// use dictFromJSON
}
} catch let error as NSError {
print(error)
}

Swift2

   init(data: NSData){  // ~this chunk~
do {
self.json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as! [String:AnyObject]

} catch {
print("error: \(error)")
self.json = nil
}
}

for more information tutorial1, tutorial2

How to pass no options to NSJSONSerialization.JSONObjectWithData in Swift

In swift 2 you should use the empty array [] to indicate no options:

NSJSONSerialization.JSONObjectWithData(data, options: [])

NSJSONSerialization.JSONObjectWithData returns weird array instead of dictionary

It's not an array, it's your NSMutableDictionary.

It looks like that when printed in the debugger: there's 3 entries, each one has a key and a value.

Do ALT+CLICK on dataDictionary and read the Xcode tip, you'll see the type.



Related Topics



Leave a reply



Submit