9pc3zg
Last Updated: February 25, 2016
·
24.03K
· anthonylevings
Speechrocket4 square

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

Say Thanks
Respond

2 Responses
Add your response

17454
0 ffbqyiyugtaqwg sfdnjyedwhno4iugswwpjywmr0podq0zdwdberdvza4e6eyit625zlakrp0xr

Simple and fast, thank's!

over 1 year ago ·
17982
0 cv5yqjlqoefj2ljz2gf qukdpa3v2qzzhjliqu1miez51k74apvkhrbb ite71mn jbcwpthntue

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 ·