Generally, you should use a JSON serializer library (e.g. NSJSONSerialization
) in order to obtain a JSON from a JSON representation and not try to create the JSON yourself.
A JSON representation is a NSDictionary
or NSArray
object containing other objects which recursively represent your JSON. Your URL will be represented as a NSString
.
What you need to do is simply have a valid URL as a NSString
, properly encoded according RFC 3968 and assign it the JSON representation, e.g.:
NSURL* url = ...;
NSDictionary* jsonObject = @{@"url": [url path]};
Now, you can serialize the JSON representation to a JSON:
NSError* error;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:jsonObejct
options:0
error:&error];
That's it, and you don't bother how the JSON encoded string looks like (encapsulated in the NSData
object as a UTF-8 character sequence).
Purposefully, when you POST this JSON, you SHOULD specify a corresponding request header:
ContentType: application/json
which lets you just use the JSON data as body data as is:
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
request.HTTPBody = jsonData;
Side note: [url path]
returns a URL as a string according RFC 1808 which is obsoleted by RFC 3968 since January 2005 already. Today, there are newer APIs since iOS 7.0, see NSURLComponents
.