Converting JSON into an Objective-C object (Xcode for iOS)
// Retrieve local JSON file called example.json
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"example" ofType:@"json"];
// Load the file into an NSData object called JSONData
NSError *error = nil;
NSData *JSONData = [NSData dataWithContentsOfFile:filePath options:NSDataReadingMappedIfSafe error:&error];
// Create an Objective-C object from JSON Data
id JSONObject = [NSJSONSerialization
JSONObjectWithData:JSONData
options:NSJSONReadingAllowFragments
error:&error];
Finally apply introspection to the object to find out whether it is a dictionary, array, etc. and to then make use of it accordingly - see http://developer.apple.com/library/ios/#documentation/General/Conceptual/CocoaEncyclopedia/Introspection/Introspection.html
If you want to retrieve JSON from a URL or roll your own JSON inside your app, then see the full post here: http://sketchytech.blogspot.co.uk/2012/04/json-and-xcode-ios-basics.html
Related protips:
Written by Anthony Levings
Related protips
2 Responses
Simple and fast, thank's!
over 1 year ago
·
NSString *converEnvoi =[nEnvoi stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *result = [NSString stringWithContentsOfURL:[NSURL URLWithString:converEnvoi] encoding:NSUTF8StringEncoding error:NULL];
NSString *new = [result stringByReplacingOccurrencesOfString: @"[" withString:@""];
result = [new stringByReplacingOccurrencesOfString: @"]" withString:@""];
if (result)
{
NSLog(@"LOC RESULT: %@", result);
NSDictionary *resultDict = [NSJSONSerialization JSONObjectWithData: [result dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error: &error];
NSArray *resultsArray = [resultDict objectForKey:@"iddep"];
if(resultsArray.count > 0)
{
}
}
RESULT: {"iduti":"142","iddep":"25"}
Bug : NSArray *resultsArray = [resultDict objectForKey:@"iddep"];
Merci d'avance
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Xcode
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#