Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I would like to see some concrete example(s)/tutorial on how to GET and POST data to and from a URL using NSJSONSerialization class.

I know how to actually GET the data , it is the POST which is confusing to some degree. Any helpful pointers will be much appreciated..

share|improve this question
add comment

1 Answer 1

up vote 7 down vote accepted

You don't use the NSJSONSerialization class for posting data. You use the NSURL* API (NSURL, NSURLConnection, NSURLRequest, etc.) instead.

NSURL *url = [NSURL URLWithString:@"http://example.com/foo.php"];
NSMutableURLRequest *rq = [NSMutableURLRequest requestWithURL:url];
[rq setHTTPMethod:@"POST"];

NSData *jsonData = [@"{ \"foo\": 1337 }" dataUsingEncoding:NSUTF8StringEncoding];
[rq setHTTPBody:jsonData];

[rq setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[rq setValue:[NSString stringWithFormat:@"%ld", (long)[jsonData length]] forHTTPHeaderField:@"Content-Length"];

[NSURLConnection sendAsynchronousRequest:rq completion:^(NSURLResponse *rsp, NSData *data, SError *err) {
    NSLog(@"POST sent!");
}];
share|improve this answer
    
This does not compile for me on XCode 5? Also, how do you serialize objects? –  aledalgrande Dec 25 '13 at 23:40
    
@aledalgrande Xcode is not a compiler. (And unless you post specific compiler errors, there's no hope I can help you.) What do you mean by "serializing objects"? Serializing generic, custom objects is not trivial, you could get away with implementing the NSCoding protocol, but you may need something more complex -- again, based on the specific use case. –  user529758 Dec 26 '13 at 0:04
    
So is there no generic way in Objective C of serializing an object to JSON like there is in Java or Ruby? Do you have to resort to these hardcoded strings? –  aledalgrande Dec 26 '13 at 5:14
1  
@aledalgrande If your objects are property list types (i. e. ones that are trivial to serialize: numbers, strings, dates, Booleans, and arrays and dictionaries of them), then you can serialize them to plists or JSON. Not otherwise. –  user529758 Dec 26 '13 at 8:26
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.