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
Swift Do Subclasses Inherit Initializers
Mysterious "Cryptographic Verification Failure" Error on MACos Sierra, Xcode 8
Square Video Using Avfoundation
How to Update a Swiftui View State from Outside (Uiviewcontroller for Example)
Gmsmapview Animatetocameraposition Zoom in - Zoom Out Animation
Impelementation of Rtcdatachannel of Webrtc in iOS
Subview Gesture Recognizer Not Being Called
Crashing While Collection View Cell Deletion Because of "Uicollectionviewlayoutattributes"
Save Video to a Custom Album Using Photos Framework in iOS
Scene Kit Memory Management Using Swift
How to Add Followed Text to Uitextfield
Google Cloud Messaging Bridging Header Import Fails
Sinch Integration in Swift Project
Change Selected Row Label Color in Picker View Swift 1.2
Draw Button on Top of Avplayer
Swift 2 Cannot Invoke 'Fseventstreamcreate' with an Argument List of Type
The Array Value Should Be Sort Like (Alphabetic, Numbers and Special Characters)