Search code examples
objective-cjsoncocoa-touchhttprequestnsjsonserialization

JSON format and objective-c


My app needs to submit a JSON payload to a server, the server wants the format like so:

{
"recipient_emails" :["[email protected]", "[email protected]"]
}

All I can seem to create is this format:

{
    "recipient_emails" = ("[email protected]", "[email protected]");
}

What I'm submitting doesn't work, which I can't tell if it's a server issue with our stmp mail server or the format of the JSON i'm submitting.

Here is how I create the json:

    //Grab the data (from NSManagedObject)
    NSString *emailData = [[NSString alloc] initWithData:self.submissionRecipients encoding:NSUTF8StringEncoding];

    //Extract all the separate email address
    NSArray *emails = [emailData componentsSeparatedByString:@","];

    //If there are some there (which should always be)
    if (emails) {
        NSError *error;

        //Add the array to an NSDictionary with key and convert to JSON
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:[NSDictionary dictionaryWithObject:emails forKey:@"recipient_emails"] options:0 error:&error];

        //Add json to HTTPRequest
        [theRequest setHTTPBody:jsonData];

        //Print out for debug purposes
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:nil];
        NSLog(@"%@", dic);
    }

Solution

  • The description of NSArray uses parenthesis - don't worry, if you use NSJSONSerialization, the generated JSON will properly contain square brackets.