Wednesday, January 13, 2016

Objective C parsing JSON response



We all know that JSON is the most suitable data format for to and fro of the data through mobile services as it is light weight and the format is pretty easy to read and write.

In this post let's discuss on how to parse JSON response from server. 

We got a response from the service in NSData format and we need to parse it, that means need to convert in any of the below listed readable and writable formats as we can't directly play withe NSData format of the response.

  • NSString
  • NSDictionary
  • NSArray


We can do it using the same NSJSONSerialization class which we used in my earlier post to prepare a JSON string Object.

 id *response = [NSJSONSerialization JSONObjectWithData:responseData    
                                       options:NSJSONReadingAllowFragments error:&error];


At the server end, backend developers can send the data in dictionary format or in an array format. So until unless we have a perfect handshake between backend developer, we can't assume the received data format.

As we can't assume the received data format, I have taken it into an id object. Now, it is a good practice and also often it is mandatory to check the received data format from server to play with the data.

We can check the data format using the NSObject introspection methods like shown below.


if ([response isKindOfClass:[NSDictionary class]]{

    NSDictionary *responseDict = (NSDictionary*)response;
}

if ([response isKindOfClass:[NSArray class]]{

    NSArray *responseArr = (NSArray*)response;
}

if ([response isKindOfClass:[NSString class]]{

    NSString *responseStr = (NSString*)response;
}


Last but not the least, let's see what is that option parameter here. Here are the different JSON reading options.

 NSJSONReadingMutableContainers = (1UL << 0),
 NSJSONReadingMutableLeaves = (1UL << 1),
 NSJSONReadingAllowFragments = (1UL << 2)



Hope this post is useful. Feel free to comment incase of any queries.