1

I am new in iOS. I created a JSON NSDictionary like this:

NSArray *keys = [NSArray arrayWithObjects:@"User", @"Password", nil];
NSArray *objects = [NSArray arrayWithObjects:@"Ali", @"2020", nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

And then I could convert it to NSString via two mechanisms:

1)

NSError *error; 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:&error];

NSString *jsonString = nil;
if (! jsonData) {
     NSLog(@"Got an error: %@", error);
} else {
     jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

2)

NSString *jsonString = [jsonDictionary JSONRepresentation];

In the second way I get this warning :

Instance method '-JSONRepresentation' not found (return type defaults to 'id')

But when I run the project, both of the mechanisms works fine:

NSLog(@"Val of json parse obj is %@",jsonString); 

Do you know how can I remove the warning in the second way?

My main goal is POST this json String to an external database using RESTful Web Service. Basically which way is better considering my main goal?

Ali
  • 9,800
  • 19
  • 72
  • 152

5 Answers5

9

You should use NSJSONSerialization as it is faster and comes directly with iOS SDK as long as your "target audience" is iOS5+

To POST the data to your web service you need the create a request along these lines...

NSDictionary * postDictionary = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"value1", @"value2", nil]
                                                                  forKeys:[NSArray arrayWithObjects:@"key1", @"key2", nil]];

NSError * error = nil;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:postDictionary options:NSJSONReadingMutableContainers error:&error];

NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"your_webservice_post_url"]];
[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:jsonData];

NSURLConnection * myConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:YES];

Please read up on NSURLConnectionDelegate protocol.

Naeem
  • 789
  • 1
  • 10
  • 23
Peter Pajchl
  • 2,699
  • 21
  • 24
  • I used the code but nothing posted to my external database. I tried [1](http://stackoverflow.com/questions/4456966/how-to-send-json-data-in-the-http-request-using-nsurlrequest) and [2](http://stackoverflow.com/questions/3566516/simple-http-post-example-in-xcode?rq=1) but they didn't work also. can you guess what is the problem? I can successfully connect the database and GET but not POST – Ali Aug 09 '12 at 14:20
  • Did you execute some type of connection with the above request? [You should never use synchronous connections unless having some good reason but for this purpose] - `[NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error: &error];` – Peter Pajchl Aug 09 '12 at 14:28
  • I updated the answer to show the NSURLConnection in it. There are better ways of implementing such connection but that is out of scope of this question. – Peter Pajchl Aug 09 '12 at 14:34
  • That was what I exactly done by the second link. But you are right I may ask it as a new question. – Ali Aug 09 '12 at 14:40
4

For iOS 5.0 > :

Use NSJSONSerialization like this :

NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
NSString *resultAsString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
 NSLog(@"jsonData as string:\n%@ Error:%@", resultAsString,error);

For < iOS 5 :

Use json-framework a third party library that uses category for NSDictionary to provide json string :

 NSString *jsonString = [dictionary JSONRepresentation];

 //with options
 NSString *jsonString = [dictionary JSONStringWithOptions:JKSerializeOptionNone error:nil]
Paresh Navadiya
  • 38,095
  • 11
  • 81
  • 132
  • That's what I did exactly regarding `JSONRepresentation`. Take a look at my question. Which one is better considering my case? – Ali Aug 09 '12 at 12:06
  • And also the `warning` I got on `JSONRepresentation` – Ali Aug 09 '12 at 12:08
  • use NSJSONSerialization its best – Paresh Navadiya Aug 09 '12 at 12:09
  • 1
    SBJSON and JSONKit is thirdparty library . So to use them u need to add them in your project. NSJSONSerialization is in built apple's library – Paresh Navadiya Aug 09 '12 at 12:12
  • Yes, I know that. what about my case (talk to a **Web Service**)? And please let me about your reason. – Ali Aug 09 '12 at 12:18
  • I appreciate for your suggestion. I think you are right about `NSJSONSerialization` @Peter described it in a better way. cheers. – Ali Aug 09 '12 at 13:08
1

This will help you... Convert NSDictionary to JSON with SBJson

Community
  • 1
  • 1
alloc_iNit
  • 5,173
  • 2
  • 26
  • 54
  • It is another mechanism to convert the `Dictionary` to `String`. OK but which one is better considering my main goal which is talk to a `Web Service`? :) – Ali Aug 09 '12 at 11:54
  • We can use `NSJSONSerialization` instead of `SBJson`. Which one is better in my case? – Ali Aug 09 '12 at 11:55
0

use this way i hope it will help you

 NSArray *keys = [NSArray arrayWithObjects:@"User", @"Password", nil];
 NSArray *objects = [NSArray arrayWithObjects:@"Ali", @"2020", nil];
 NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

 NSError *error = nil;
 // NSError *error; 
 NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:&error];


 id result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];

 NSLog(@"\n\n\n id for json==%@ \n\n\n\n\n",result);
Naeem
  • 789
  • 1
  • 10
  • 23
Senthilkumar
  • 2,471
  • 4
  • 30
  • 50
  • 1
    Please take a look at the end of my question. What is the use of this way considering my main goal? – Ali Aug 09 '12 at 12:04
0
JSON DEFAULT METHOD......

+(NSDictionary *)stringWithUrl:(NSURL *)url postData:(NSData *)postData httpMethod:(NSString *)method { 

NSDictionary *returnResponse=[[NSDictionary alloc]init];

@try {
 NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:180]; [urlRequest setHTTPMethod:method];

if(postData != nil)
{
    [urlRequest setHTTPBody:postData];
}

[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[urlRequest setValue:@"text/html" forHTTPHeaderField:@"Accept"];

NSData *urlData;
NSURLResponse *response;
NSError *error;
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
                                returningResponse:&response
                                            error:&error];
returnResponse = [NSJSONSerialization
                  JSONObjectWithData:urlData
                  options:kNilOptions
                  error:&error];
} @catch (NSException *exception) { returnResponse=nil; } @finally { return returnResponse; } }

Return Method :

+(NSDictionary )methodName:(NSString)string { 
NSDictionary *returnResponse; NSData *postData = [NSData dataWithBytes:[string UTF8String] length:[string length]]; NSString *urlString = @"https//:..url...."; returnResponse=[self stringWithUrl:[NSURL URLWithString:urlString] postData:postData httpMethod:@"POST"];
return returnResponse; 
}
Arjun
  • 1
  • You posted this answer on more than one question. Please do not do that. Each question should be answered on its own terms; if the answers are the same, then one of the questions should be marked as a duplicate of the other. You will be able to vote to do this when you have enough reputation. – elixenide Nov 27 '15 at 02:28