Skip to content

Posting NSDictionary as JSON

tilowestermann edited this page Jan 4, 2012 · 2 revisions

Recently, I had to send some data which was available as a NSDictionary as a JSON string to a remote server. The following snippet accomplishes this task:

- (void)sendAsJSON:(NSDictionary*)dictionary {

    RKClient *client = [RKClient clientWithBaseURL:@"http://restkit.org"];        

    // create a JSON string from your NSDictionary 
    id<RKParser> parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:RKMIMETypeJSON];
    NSError *error = nil;
    NSString *json = [parser stringFromObject:obj error:&error];

    // send your data
    if (!error)
        [[RKClient sharedClient] post:@"/some/path" params:[RKRequestSerialization serializationWithData:[json dataUsingEncoding:NSUTF8StringEncoding] MIMEType:RKMIMETypeJSON] delegate:self];

}