Illep
Illep

Reputation: 16849

Convert NSData to JSON

I have a NSData object, i need to convert it a NSDictionary object.

NSData *data = ....;

Now i need to convert this to a NSDictionary, How can i do this programatically ?

note: After i save the NSData to the NSDictionary i should be able to access key value pairs of the NSDictionary.

I don't have a code to demonstrate my workings so far, I have only created the NSData object, and have no clue to continue :)

Upvotes: 6

Views: 14063

Answers (3)

MartinMoizard
MartinMoizard

Reputation: 6680

You can subclass MKNetworkOperation and override the responseJSON method with the following:

-(id) responseJSON
{
    NSString *rawJSON;
    id jsonValue = nil;
    if ((rawJSON = [[NSString alloc] initWithData:[self responseData] encoding:NSUTF8StringEncoding]) != nil) {
        SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
        if ((jsonValue = [jsonParser objectWithString:rawJSON]) == nil) {
            NSLog(@"This string doesn't seem to be JSON: '%@'\nraw Data : '%s'", rawJSON, (char *)[[self responseData] bytes]);
            return [self responseString];
        }
    }
    else {
        NSLog(@"This data doesn't seem to be an UTF8 encoded string: %@", [self responseData]);
        return [self responseString];
    }

    return jsonValue;
}

Upvotes: 3

timothy
timothy

Reputation: 4487

I highly recommend invoking SBJSON framework, it saved my time for many times, exactly finished my work and easily to use. You don't need to know the details of the conversion algorithm, just download and invoke it.

You might want to download it from here, then follow this tutorial to get your things done.

Upvotes: 1

Omer Waqas Khan
Omer Waqas Khan

Reputation: 2413

Please check this link of stack overflow, I have already consumed the JSON services, it will help you a lot. All of the coding is there.

JSON Data Conversion

And here is the tutorial with sample project

JSON Parse Tutorial

Hope you would find it helpful

Upvotes: 3

Related Questions