title: Objective-C / iOS: Converting an array of objects to JSON string
body: <p>I am currently experimenting with the use of JSON for internet data transfer. I have been successful in receiving a JSON string and converting it into an <code>NSDictionary</code>, but have not been able to work out how to convert an array or dictionary of objects into a JSON representation.</p>
  
  <p>I have read a number of posts and articles which explain how to create a <code>NSDictionary</code> of key/value pairs and then convert to JSON, which works fine for a simple array, but how do you achieve this when you have an array or dictionary of objects.</p>
  
  <p>So for example, I have an array of objects "contact", which I would then like to transform into a JSON string as such:</p>
  
  <pre><code>"contacts":{
      "contact":[
      {
          "id":"1"
          "first_name":"john",
          "last_name":"citizen",
          "phone":"9999 9999"
      }
      {
          "id":"1"
          "first_name":"jane",
          "last_name":"doe",
          "phone":"8888 8888"
      }
      ]
   }
  </code></pre>
  
  <p>I have a <code>NSMutableDictionary</code> which is populate a list of contact objects:</p>
  
  <pre><code>    NSMutableDictionary* contactsToBeSynced = [[NSMutableDictionary alloc] init];
      //Populate dictionary with contact objects.
      contactsToBeSynced = self.getNonSynchronisedData;
  </code></pre>
  
  <p>I then attempt to transform the dictionary of objects with the <code>NSJSONSerialization</code> method, but it fails with an error.</p>
  
  <pre><code>    NSError* error;
      NSString* jsonString;
      NSData* jsonData = [NSJSONSerialization dataWithJSONObject:contactsToBeSynced options:NSJSONWritingPrettyPrinted error:&amp;error];
      jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  </code></pre>
  
  <p>Has anyone been able to successfully do this? Would greatly appreciate some help or a point in the right direction. Cheers.</p>