JSON IPHONE: How to send a JSON request and pull the data from a server? JSON IPHONE: How to send a JSON request and pull the data from a server? json json

JSON IPHONE: How to send a JSON request and pull the data from a server?


JSON framework supports converting Arrays, Dictionaries, Strings, Numbers, and Booleans. So what you want to do is convert your data to one of these formats. Since your data is NSData easiest way is to convert it with:

NSString* stringData = [[NSString alloc] initWithData:yourData                                             encoding:NSUTF8StringEncoding];

Depending on what's in the buffer (and if your server can handle it) you may want to Base64 encode the result (check http://www.cocoadev.com/index.pl?BaseSixtyFour if you don't have a converter handy). You could even go straight from NSData to a Base64-encoded string.

Now create a dictionary with one item with key code and value stringData (from last step):

NSDictionary* jsonDictionary = [NSDictionary dictionaryWithObject:stringData                                                           forKey:@"code"];

This can be easily converted to JSON. Just import JSON.h in your code header, then use:

NSString* jsonString = [jsonDictionary JSONRepresentation];

Dump it out and you'll see your JSON string -- something like: { "code" : "{yourstringdata}"; }. Easiest way to send this over to your server is to use the ASIHTTPRequest library with a POST method.

Once you get the result back from the server the JSON framework can parse it back into a dictionary and then you can get out the data you need:

NSDictionary* responseDict = [yourJSONResponseStringFromServer JSONValue];NSNumber* answerNum = (NSNumber *) [responseDict objectForKey:@"answer"];int answer = [answerNum intValue];