How to deserialize json object and assign to a NSDictionary in iOS

sefirosu picture sefirosu · Aug 30, 2012 · Viewed 9.1k times · Source

This is my code for handling server response.

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
 {
 NSLog(@"connectionDidFinishLoading : %@", [[NSString alloc] initWithData:self.data    encoding:NSUTF8StringEncoding]);
 }

This is the message Server response to me, NSLog JSON displays in console.

connectionDidFinishLoading : {"ErrorCode":"CssParameterException","ErrorMessage":"An error has occurred, please try again later.","Success":false}

My question is: how do I deserialize the JSON and store it into a local variable NSDictionary *jsonData?

Any suggestions? Please give me some code example, thanks!

Answer

msk picture msk · Aug 30, 2012
NSError *e = nil
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData: responseData options: NSJSONReadingMutableContainers error: &e];

If you have NSString response

NSError *e = nil
    NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData: [responseString dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error: &e];