Get server JSON response as a NSDictionary

98 views Asked by At

I'm trying to get server response NSData into NSDictionary but it returns following NSCFString.

NSError *error;
NSDictionary* jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];

And can't access data using objectForKey. Give me a way to get this response as a NSDictionary or conversion mechanism. Cannot get anything NSJSONSerialization with kNilOptions returns nil.

2

There are 2 answers

2
Dis_Pro On

According to this question can't serialize with NSJSONSerialization with option kNilOptions.

So first we need to get above serialized JSON as a NSString and then convert it into NSData again. Then you can convert it back to NSDictionary with kNilOptions.

NSString* jsonString = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];

NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id jsonDictionary = [NSJSONSerialization jsonData options:0 error:nil];
0
Mladen Dryankov On

After using NSJSONSerialization for a while I got more problems than solutions while parsing the data.

I would kindly advice you to use SBJson library which may be found as cocoapod and serves me well for many projects without any issues for many many years

E.g. [https://cocoapods.org/pods/SBJson][1]