JSON parsing using NSJSONSerialization in iOS
First of all in your JSON
response dictionary
, under the key 'RESPONSE' you have a array not a dictionary
and that array contains dictionary
object.
So to extract username and email ID so as below
NSMutableDictionary *response = [[[json valueForKey:@"RESPONSE"] objectAtIndex:0]mutableCopy];
NSString *username = [response valueForKey:@"username"];
NSString *emailId = [response valueForKey:@"email"];
iOS - Parsing JSON Dictionary with NSJSONSerialization in Swift
The result of the deserialization will be an array:
let data = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
do {
let dataArray = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! NSArray
for event in dataArray {
print(event)
}
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
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);
}
}
Parsing JSON using NSJSONSerialization
NSJSONSerialization can take a chunk of JSON data and turn into objects and it can do the same in the other direction that is by taking objects and converting them into the JSON data.
For easy understanding of NSJSONSerialization and interaction with Twitter, i would recommend you to use THIS and THIS tutorials.
Hope this helps!
Using NSJSONSerialization to parse JSON
Your json that you parsed contains a dictionary named data
. Within that dictionary is an array of current_condition
. Keep drilling down through the data structures to find the attributes you are looking for:
NSDictionary *data = [parsedJSON objectForKey:@"data"];
NSArray *currentConditions = [data objectForKey:@"current_condition"];
NSDictionary *condition = [currentConditions objectAtIndex:0];
NSString *tempC = [condition objectForKey:@"temp_C"];
Parsing JSON with NSJSONSerialization - NSException thrown
The JSON object you've shown has 348 listed as an integer value. So when NSJSONSerialization
gets its hands on it, it converts it to an NSNumber. You'll need to call -[NSNumber stringValue]
on [jsonObject objectForKey:@"data"]
to convert the NSNumber
to an NSString
.
Parse json with NSJSONSerialization class using objectForKey in iOS
You have to access the 0
item of item
array:
NSArray *mainArray = [item objectAtIndex:0];
(NSDictionary *obj in mainArray) {
NSString *name = [obj objectForKey:@"name"];
}
When you got this error: -[__NSArrayM objectForKey:]
, you need to realize that the object that you're trying to access isn't a dictionary. It's an array (__NSArrayM
), so you have to first access the 0 index, and then starting exploring the dictionary.
Take a look at this amazing tutorial, from Ray Wenderlich, that explains everything about crashes.
Parsing data using NSJSONSerialization.JSONObjectWithData() but cannot access Array groups only strings
You can try like this way, declare 3 array first.
var logArr: [[String: AnyObject]] = [[String: AnyObject]]()
var imageArr: [[String: AnyObject]] = [[String: AnyObject]]()
var valveArr: [[String: AnyObject]] = [[String: AnyObject]]()
Now use this array where you are getting response
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments) as? Array<Dictionary<String, AnyObject>> {
for item in json {
if let dict = item as? Dictionary<String, AnyObject> {
if let nameStr = dict["name"] as? String {
incidentList.valueStr = nameStr
}
if let codeStr = dict["dma"] as? String {
incidentList.valueStr = codeStr
}
if let region = dict["region"] as? String {
incidentList.valueStr = region
}
if let ncLead = dict["nc_lead"] as? String {
incidentList.valueStr = ncLead
}
if let logs = dict["logs"] as? [[String: AnyObject]] {
self.logArr = logs
}
if let valveOps = dict["valveOps"] as? [[String: AnyObject]] {
self.valveArr = valveOps
}
if let images = dict["images"] as? [[String: AnyObject]] {
self.imageArr = images
}
Related Topics
How to Use Afnetworking or Sthttprequest to Make a Request of a Soap Web Service
Pinch to Zoom Effect on Uiimageview Inside Scrollview
How to Get 18-Digit Current Timestamp in Swift
Alert When New Version of iOS App Is Available
Share Datas Between Two Apps with iOS 8 App Groups (Using Nsuserdefaults)
What's Wrong Here: Instance Member Cannot Be Used on Type
Can't Send Push Notifications Using the Server API
Ios/C: Convert "Integer" into Four Character String
Facebook Registration:The Operation Couldn't Be Completed (Com.Facebook.Sdk Error 2)
Open iOS 11 Files App via Url Scheme or Some Other Way
Ios: Usage of Self and Underscore(_) with Variable
What Is the Swift Preprocessor Equivalent to iOS Version Check Comparison
JSON Parsing Using Nsjsonserialization in iOS
Cannot Show Modal Viewcontroller in iOS7
Itunes Connect: Can't See Build
Will Fork() in iOS App Likely Be Rejected by Apple's Vetting Process