Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :)

like image 926
Illep Avatar asked Jan 23 '12 13:01

Illep


3 Answers

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;
}
like image 169
MartinMoizard Avatar answered Nov 09 '22 10:11

MartinMoizard


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

like image 45
Omer Waqas Khan Avatar answered Nov 09 '22 12:11

Omer Waqas Khan


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.

like image 1
Skyler Avatar answered Nov 09 '22 12:11

Skyler