Wednesday, January 13, 2016

Objective C preparing JSON object



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

In this post let's discuss on how to prepare a JSON object from a list of information whether it's a key based information (NSDictionary) or a index based information (NSArray).

Let's say we have user profile information in a dictionary as shown below.

NSDictionary *userInfoDict = [NSDictionary alloc] initWithObjectsAndKeys:

@"Karunakar",@"firstname",
@"Bandikatla",@"lastname",
@"Male",@"gender",
@"India",@"country",
@"Degree",@"education",

nil];

We need to send the above information to a service. Obviously, we can't send a dictionary object to a service. We need to convert it to string format and on the server side this information should be parsable. So we need to convert it to a JSON string.

Let's see how to convert a dictionary information to a JSON string using Objective C.

Using NSJSONSerialization, we can convert this dictionary to NSData and then we can pass it to service or we can convert this to NSString from NSData and then pass it as a JSON formatted string as shown below.

NSData *jsonData = [NSJSONSerialization dataWithJSONObject: userInfoDict
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];

Sometimes, we may even need to upload user information or some other information as a file to the server. In this case we can directly give NSData to file upload service. We need to check the error value to make sure things are fine before sending it to the server.

Last but not the least, let's see what is that 'options' parameter here. If we are uploading this user info file to the server, If we open that file, If we want that file to be in a JSON readable format like shown below, the option should be NSJSONWritingPrettyPrinted. If you are not bothered about the pretty writing format, you can ignore that parameter.














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