0

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.

isuru
  • 3,385
  • 4
  • 27
  • 62
  • Please check what type does the method returns. – iPeter Jun 03 '19 at 05:35
  • @iPeter It's NSCFString – isuru Jun 03 '19 at 05:43
  • Most likely `data` doesn't actually represent a JSON dictionary. Create a string from `data` and see what you are actually getting. – rmaddy Jun 03 '19 at 06:02
  • @rmaddy using NSJSONReadingAllowFragments it returns correct JSON. – isuru Jun 03 '19 at 06:07
  • 1
    That contradicts everything you've stated. You state that at the moment, `jsonDict` is really an `NSCFString` and not an `NSDictionary`. Therefore `data` does not represent a JSON dictionary. If you convert `data` to a string and print it out, you will be able to see the actual JSON you are getting. Then you can figure out how to get the correct JSON from wherever you are getting the data from. – rmaddy Jun 03 '19 at 06:12
  • Print `data`, then we could understand what your issue, because now we don't understand. – Larme Jun 03 '19 at 09:35
  • yes, show DATA what you receive in response. – Bhawin Ranpura Jun 04 '19 at 10:09
  • NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error]; – Bhawin Ranpura Jun 04 '19 at 13:45

2 Answers2

0

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];
Dis_Pro
  • 633
  • 1
  • 10
  • 21
0

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]