iPhone Development: Encoding and decoding JSON in IOS

JSON(Java Script Object Notation), according to its definition its an open standard format that send data to transmit in a key value pair and is easy to readable by human. In, IOS we can encode and decode our data into JSON or from  JSON using in built class provided by Xcode and is named as NSJSONSerialization. The most common method used in day to day programming are

1)  + (NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error
2)  + (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error

The first methods allow us to convert our data into JSON object.As per its description provided in documentation it says, returns JSON data from a Foundation object. If obj will not produce valid JSON, an exception is thrown.Setting the NSJSONWritingPrettyPrinted option will generate JSON with whitespace designed to make the output more readable. If that option is not set, the most compact possible JSON will be generated.

And for second method it says, Returns a Foundation object from given JSON data.
The data must be in one of the 5 supported encodings listed in the JSON specification: UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE. The data may or may not have a BOM. The most efficient encoding to use for parsing is UTF-8, so if you have a choice in encoding the data passed to this method, use UTF-8.

In short, first method is used to convert data into JSON and second method is used to read JSON data.

To create a JSON, we will require two thing key and value.We will create two arrays static Array,  in this array we will add our keys for JSON and dynamic Array which contains value for the keys, We can also send an array inside our JSON and then convert the data into JSON using NSJSONSerialization.  Below is the code that show how to decode data into JSON

   NSMutableArray *staticAray = [[NSMutableArray alloc] initWithCapacity:0];
   NSMutableArray *dynamicAray = [[NSMutableArray alloc] initWithCapacity:0];
   
    [staticAray addObject:@”auth_token”];
    [staticAray addObject:@”shop_id”];
    [staticAray addObject:@”comment”];
    [staticAray addObject:@”r_earn”];
    [staticAray addObject:@”tag_friend”];
   
    [dynamicAray addObject:@”OAJHPRbc6l”];
    [dynamicAray addObject:@”1254″];
    [dynamicAray addObject:@”Comments”];
    [dynamicAray addObject:@”Rewardearned”];

  //sending array by JSON
  NSMutableArray *taggedContactArray = [[NSMutableArray alloc]initWithCapacity:0]
  for (NSDictionary *dict in invitedContactArray)
    {
        if (![[dict valueForKey:@”userName”] isEqualToString:@””])
        {
            [selectedContactArray addObject:[dict valueForKey:@”userName”]];
            [taggedContactArray addObject:dict];
        }
    }
  [dynamicAray addObject:tagFriendArray];

As we have our keys and value with us its time to create JSON. First we create a dictionary as dictionary contains key value and our JSON is also a key value type. Then we convert that dictionary into JSON data using dataWithJSONObject method of our NSJSONSerialization class. This is encoding of object into JSON Data. Below is the code that do same thing as mentioned/discussed


 NSDictionary *data = [NSDictionary dictionaryWithObjects:dynamicAray forKeys:staticAray];
 NSError *writeError = nil;

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

To decode we will use our second method called JSONObjectWithData . It will give us dictionary

 id mainDict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&writeError];
    NSLog(@”main dict ==%@”,mainDict);

Its all with JSON using NSJSONSerialization.