I have generated JSON data from Java Restful WebServices and I need to put into the Objective C code. How can I use the JSON data and integrate into Objective C? The IDE has generated the local URL, how can I use the generated JSON data in other machine. Thank you
Have a look at NSURLConnection to retrieve the JSON from your web service. Then you can make use of NSJSONSerialization to parse it.
Use any of the many JSON parsers available. This question compares a few of them: Comparison of JSON Parser for Objective-C (JSON Framework, YAJL, TouchJSON, etc)
You can request the NSData from the URL and then use NSJSONSerialization to interpret it. For example:
NSURL *url = [NSURL URLWithString:#"http://www.put.your.url.here/test.json"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
NSLog(#"%s: sendAsynchronousRequest error: %#", __FUNCTION__, error);
return;
}
NSError *jsonError = nil;
NSArray *results = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
if (jsonError) {
NSLog(#"%s: JSONObjectWithData error: %#", __FUNCTION__, jsonError);
return;
}
// now you can use the array/dictionary you got from JSONObjectWithData; I'll just log it
NSLog(#"results = %#", results);
}];
Clearly, that assumed that the JSON represented an array. If it was a dictionary, you'd replace the NSArray reference with a NSDictionary reference. But hopefully this illustrates the idea.
Related
Trying to parse simple JSON data from Instagram but stuck with this problem.
JSON data returns truncated in application, but everything is ok via browser on my mac.
Tried to do that many different ways, but all the same.
First way:
NSURL *instaGetRecentOwnerPhotosURL = [NSURL URLWithString:#"https://api.instagram.com/v1/users/self/media/recent/?access_token=MY_PROPER_TOKEN"];
NSData *jsonData = [NSData dataWithContentsOfURL:instaGetRecentOwnerPhotosURL];
Another way, assync:
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:#"https://api.instagram.com/v1/users/self/media/recent/?access_token=MY_PROPER_TOKEN"]];
__block NSDictionary *json;
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
json = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
NSLog(#"Async JSON: %#", json);
}];
JSON data returns like that:
screenshot of truncated json
Absolutely have no idea what is wrong.
It's not truncated. The log simply only shows part of the output. If it was really truncated it either wouldn't have parsed at all or it would just have fewer entries. But the data did parse. There is nothing wrong with json.
BTW - do proper error checking:
NSError *error = nil;
json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (json) {
// Data is good. Work with 'json'
} else {
NSLog(#"Unable to parse JSON. Error: %#", error);
}
I’ve never used an API in conjunction with web services before and I’m having trouble parsing the JSON data I’m receiving from Flickr’s API. The only thing I do know (from all the things I have read) is that it is easy and very simple. About as far as I can get is returning a string in the console. Using a dictionary returns null and or an error. What am I missing? I want to be able to pull out the id and owner so that I can get the photo url.
This returns data on my photo:
NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#”%#”, json); //this returns data on my photo
This returns null(resultDict) and error 3840:
NSString *requestString = #”https://api.flickr.com/services/rest?&method=......etc;
NSURL *url = [NSURL URLWithString:requestString];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSURLSessionDataTask *task = [session dataTaskWithURL:url
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSMutableDictionary *resultdict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSLog(#”%#”, resultDict); //returns null
If (error != nil) { NSLog(#”%#”, [error localizedDescription]); }
else { self.myDict = [[resultDict objectforKey:#”photos”] objectAtIndex:0];
NSLog(#”%#”, self.myDict); }
}];
[task resume];
To check if I have an array of dictionaries I did the following and it returned 0:
NSMutableArray *resultArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainer error:&error]; error:&error];
NSLog(#"%lu", (unsigned long)resultArray.count);
Are you sure that
[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
returns a Dictionary and not an Array of Dictionnaries?
EDIT :
Can you try to use this to request the API please?
I checked in my projects, my reponses seems to have the same syntax as yours.
Only the code I use is different.
(If you could give us the full URL you've to call, it would be easier for us ^^')
NSString *str=#"YOUR URL";
NSURL *url=[NSURL URLWithString:str];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse:&response error: &error];
NSMutableDictionary* resultList = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:nil];
I copied it without the errors. I let you manage that ^^
NSMutableDictionary ***resultdict** = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSLog(#”%#”, **resultDict**); //returns null
resultdict and resultDict are not the same variables. I bet you have an instance variable or a global variable somewhere named resultDict. Instance variables should start with an underscore, among other reasons because it avoids problems like this.
For question maker this answer won't be actual but maybe for them who will face with such problem.
I had the same problem when tried to get data from flickr.photos.getRecent method. I forgot to add into URL parametrs value nojsoncallback=1.
Without it you get response in JSONP.
i'm trying to load big file from server, but when it's loading always very slow.
Can you suggest me method, how to fast load more, then 200k objects ?
Printing description of data:
(NSData *) data = 0x08e51d80 151341098 bytes
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if (error)
{
NSLog(#"Error,%#", [error localizedDescription]);
}
else
{
NSLog(#"%#", [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
}
}];
Two points:
You can use file output stream for network request instead of holding the whole NSData in memory. For example, AFNetworking supports such option.
You can use a SAX parser with stream support for deserialising your data from file, to, again, avoid loading whole XML into memory. For example, NSXMLParser does support stream parsing.
Here's the example of setting up NSXMLParser:
NSInputStream *fileStream = [NSInputStream inputStreamWithURL:temporaryXMLFileURL];
NSXMLParser *parser = [[NSXMLParser alloc] initWithStream:fileStream];
parser.delegate = yourParserDelegate;
BOOL result = [parser parse];
You can implement your parsing & object instantiation code in a class adopting NSXMLParserDelegate, there're a lot of examples over the internet, even one from Apple.
Please keep in mind that all this tricks won't speed up downloading of your large file from the internet, it depends entirely on your connection speed. My approach would only help to reduce your application memory footprint (hence reducing the risk of your app being jettisoned by iOS because of memory pressure).
Switch to JSON. JSON will load and parse MUCH faster than XML. I have a JSON file that is 1.8 MB and it downloads and parses (I use AFNetworking for the connection) in around 7 seconds. Another tip, cache the resulting NSArray on the device so that the next time, you can load directly from that cached array and in the background request the file again and compare to the cached Array. If different, update the model with the new data.
Something like this:
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (!error) {
NSError *error = nil;
id jsonObj = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
}
}
else {
NSLog(#"Error,%#", [error localizedDescription]);
}
}];
I am new to ios,so inorder to get accesstoken, i followed the link
http://technogerms.com/login-with-google-using-oauth-2-0-for-ios-xcode-objective-c/ .so in these link they used json.h files are they mandatory.if it is yes then explain me about json github in these link.
Here is the link what you want.
https://github.com/johnezang/JSONKit
Use native NSJSONSerialization class, you can find more info on below link,
iOS NSJSONSerialization
How to use NSJSONSerialization
There is no compulsory to use JSON.h in your project. Now You can use inbuilt apple JSON parser. IF you want to download JSon library then link is
Download JSon file from here
Otherwise you can use this Inbuilt apple JSON Parser by using following method.
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves || NSJSONReadingMutableContainers error:&myError];
The full code is as below:
NSString *urlString=[NSString stringWithFormat:#"%#listcontact.php?uid=%#&page=0",LocalPath,appdel.strid]; //---- Add your URL for webservice-----
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
There are two NSURLConnection request methods AsynchronousRequest and SynchronousRequest.
(1) For AsynchronousRequest
[NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSError *error1;
NSDictionary *res=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error1];
}];
(2) For SynchronousRequest
NSData *GETReply = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil];
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:GETReply options:NSJSONReadingMutableLeaves error:&myError];
How can I use the iTunes search API from within iOS/Obj-c ?
I know of this link of course..
http://www.apple.com/itunes/affiliates/resources/documentation/itunes-store-web-service-search-api.html
I just don't understand how you use obj-c/iOS with it.
I want to be able to read the JSON results, whether they be broad or just 1 result and store the apps name (or would that be ID?), any images, rating etc in my server database (using parse.com).
How can I do that, and is that allowed by the Apple developer terms?
It looks like you just make the requests and parse the results. No auth or anything else fancy...
NSString *urlString = #"https://itunes.apple.com/search?term=jack+johnson";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (!error) {
NSError* parseError;
id parse = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&parseError];
NSLog(#"%#", parse);
}
}];
The JSON parser will yield arrays of dictionaries for collection calls and (probably) dictionaries for single objects.