I am currently working on an iPhone application that takes in data from the following source:
I am trying to figure out how to parse it into a human readable format in say a text field.
My code so far is:
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *urlString = [NSString stringWithFormat:#"http://dev.threesixtyapp.com/api/events.php?action=available&id=1"];
NSURL *url =[NSURL URLWithString:urlString];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"%#",json);
}
http://stig.github.com/json-framework/ - SBJson is a great framework for encoding/decoding JSON. I recommend you check it out...It will parse it for you into an NSDictionary, and you simply set the text of the textfield equal to the value in the NSDictionary that you want. It's pretty straightforward using this framework. Your Json should just be a string when you pass it to the SBJson functions btw
First of all you have to understand the data structure of your json.
You can use JSON Viewer to view the data structure of your json.
As I can see you are getting array of objects consisting of event_title, date_from and date_to.
NSError *error = nil;
NSArray *jsonArry = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"%#",jsonArry);
for (NSDictionary *dict in jsonArry) {
NSString * title = [dict objectForKey:#"event_title"];
NSString * dateTo = [dict objectForKey:#"date_to"];
NSString * dateFrom = [dict objectForKey:#"date_from"];
NSLog(#"title=%#,dateTo=%#,dateFrom=%#",title,dateTo,dateFrom);
}
Related
How do I extract just the "token" value from the following code? I'm looking to save this value into a string.
Is meta an array? If so how would I extract the data from the "token" value?
thanks for any help
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
Response ==> {"meta":[],"data":{"token":"IVZ2ciRkbVtDLUl3YmhwOTkyXzpRR1M3LUUsRiElfWF6T3I6dCxsRWg6di1XcyR6OTUzZHhVazdLTEJ7blU5O258d2xRTXg0VUxwQXBlNHRSOXd2VXZ1aG1RfFhQQjJsSkkoc2IuOTFyYkYodyhAe2RldXR1aDF3RClXWyhoMiU="}}
2013-07-19 15:10:23.139 appName [11190:907] {
data = {
token = "IVZ2ciRkbVtDLUl3YmhwOTkyXzpRR1M3LUUsRiElfWF6T3I6dCxsRWg6di1XcyR6OTUzZHhVazdLTEJ7blU5O258d2xRTXg0VUxwQXBlNHRSOXd2VXZ1aG1RfFhQQjJsSkkoc2IuOTFyYkYodyhAe2RldXR1aDF3RClXWyhoMiU=";
};
meta = (
);
}
I believe the data is in JSON format. In that case, this should work.
NSError *error = nil;
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:urlData options:0 error:&error];
NSString *token = [[responseDict objectForKey:#"data"] objectForKey:#"token"];
I'd just do this:
NSData *responseData = [NSData dataWithContentsOfURL:yourURL];
NSString *token = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions error:NULL][#"data"][#"token"];
It will be nil if there's any error.
In your Case, meta is an Array and data is a Dictionary. If your Response is properly formatted in JSON then you can use the below sample code to get the TokenString and metaArray.
Sample Code :
NSData *data = [NSData dataWithContentsOfURL:yourURL];
NSError* error = nil;
NSDictionary* responseDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSString *token = [[responseDict objectForKey:#"data"] objectForKey:#"token"];
NSArray *meta = [responseDict objectForKey:#"meta"];
NSLog(#"\ntoken :: %#\nmeta :: %#",token,meta);
PS : To know more about JSON response , take a look at this Answer.
In fact, I am new in iOS programming, and I am trying to learn it by myself.
I have a sectioned table view, with header sections, but I want the view to be able to collapse expand the rows in section when this section is tapped.
I use this tutorial: http://blog.paxcel.net/blog/expandablecollapsible-table-for-ios/
But In my application, I have a Json File and not a Plist file.
So I use in setCategoryArray() function:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL:
[NSURL URLWithString: #"http://......./catjsonf.php"]];
NSError* error;
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
jsonResults = [json objectForKey:#"nodes"];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
});
instead of :
NSURL *url = [[NSBundle mainBundle] URLForResource:#”CategoryList” withExtension:#”plist”];
NSArray *mainArray = [[NSArray alloc] initWithContentsOfURL:url];
But it doesn't work - should I do something else?
check out my blog it will surely help you. here is the link.
Expandable/Collapsible Table For iOS
you need to do the following things
First design your classes according to your json file as in my case it is "Category".
Once you are done with model classes you need to edit the following method to prepare array of model objects.
Hint: From json, we can directly find out our dictionary like
id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
where result can further casted to get the dictinary object. And the load data simply like the following method
- (void) setCategoryArray
{
NSURL *url = [[NSBundle mainBundle] URLForResource:#”CategoryList” withExtension:#”plist”];
NSArray *mainArray = [[NSArray alloc] initWithContentsOfURL:url];
NSMutableArray *categoryArray = [[NSMutableArray alloc] initWithCapacity:[mainArray count]];
for (NSDictionary *dictionary in mainArray)
{
Category *category = [[Category alloc] init];
category.name = [dictionary objectForKey:#"name"];
category.list = [dictionary objectForKey:#"list"];
[categoryArray addObject:category];
}
self.categoryList = categoryArray;
}
Once this done, the only thing left to edit the table view's data source and delegate methods accordingly.
I am trying to map a JSON array using the MapKit. I can get a single point on the map with the code below, but I have dozens of pins I need to mark, and I have a JSON array prepared. My code for a single point is below.
In my .h file:
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#interface MapViewController : UIViewController {
MKMapView *mapView;
NSData *data;
}
#property (nonatomic, retain) IBOutlet MKMapView *mapView;
#end
In my .m file:
NSData *data = #"[{"id":"1","name":"Jiffy Lube","lat":"21.306","lon":"-157.861"},
{"id":"2","name":"Bills
Oil","lat":"21.301","lon":"-157.863"},{"id":"3","name":"Auto Zone","lat":"21.307","lon":"-
157.862"}]";
// parse the JSON into a NSArray
NSError *error;
NSArray *array = [NSJSONSerialization JSONObjectWithData:data
options:0
error:&error];
Your JSON is an array of dictionary items. So you can just retrieve the full array via NSJSONSerialization, and then iterate through the dictionary entries in the resulting array.
First, you originally said you had JSON like the following:
[{"id":"1","name":"Jiffy Lube","lat":"21.306","lon":"-157.861"},
{"id":"2","name":"Bills Oil","lat":"21.301","lon":"-157.863"},
{"id":"3","name":"Auto Zone","lat":"21.307","lon":"-157.862"}]
So, if that's sitting in a file, "test.json" that you've included in your bundle, you could load it as so:
// load the data from local file
NSString *path = [[NSBundle mainBundle] pathForResource:#"test" ofType:#"json"];
NSData *data = [NSData dataWithContentsOfFile:path];
If you have this on a web server, you'd retrieve it like so:
// load the data from web server
NSURL *url = [NSURL URLWithString:#"http://insert.your.server/and/url/here/test.json"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// use NSData here
}];
Assuming you loaded your JSON feed into a NSData object called data, you could just do something like:
// parse the JSON into a NSArray
NSError *error;
NSArray *array = [NSJSONSerialization JSONObjectWithData:data
options:0
error:&error];
if (error != nil)
{
// handle the error as you want
}
// a few variables to be used as we iterate through the array of results
CLLocationCoordinate2D location; // coordinates of the annotation
NSMutableArray *newAnnotations = [NSMutableArray array]; // an array in which we'll save our annotations temporarily
MKPointAnnotation *newAnnotation; // the pointer to the annotation we're adding
// iterate through the array, adding an annotation to our our array of new annotations
for (NSDictionary *dictionary in array)
{
// retrieve latitude and longitude from the dictionary entry
location.latitude = [dictionary[#"lat"] doubleValue];
location.longitude = [dictionary[#"lon"] doubleValue];
// create the annotation
newAnnotation = [[MKPointAnnotation alloc] init];
newAnnotation.title = dictionary[#"name"];
newAnnotation.coordinate = location;
// add it to our array
//
// incidentally, generally I just add it to the mapview directly, but
// given that you have a didAddAnnotationViews, we'll just build up
// an array and add them all to the map view in one step after we're
// done iterating through the JSON results
[newAnnotations addObject:newAnnotation];
// clean up
[newAnnotation release];
}
// when done, add the annotations
[self.mapView addAnnotations:newAnnotations];
I'm trying to parse some JSON in iOS to get a URL from google. I've gotten pretty far (see code below), the problem is since I've never worked with JSON before, I'm not really sure how things are defined. How can I look for an object that's inside another object?
For example if I want to get the first unescapedUrl here how can I do that? I tried simply using objectForKey, but it didn't work.. I'm guessing I'm going to have to specify the exact path. How can I do that?
Here's the code I'm using:
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) //1
#define kLatestSearchURL [NSURL URLWithString: #"https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=monkey"] //2
#import "ViewController.h"
#interface NSDictionary(JSONCategories)
+(NSDictionary*)dictionaryWithContentsOfJSONURLString:(NSString*)urlAddress;
-(NSData*)toJSON;
#end
#implementation NSDictionary(JSONCategories)
+(NSDictionary*)dictionaryWithContentsOfJSONURLString:(NSString*)urlAddress
{
NSData* data = [NSData dataWithContentsOfURL: [NSURL URLWithString: urlAddress] ];
__autoreleasing NSError* error = nil;
id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (error != nil) return nil;
return result;
}
-(NSData*)toJSON
{
NSError* error = nil;
id result = [NSJSONSerialization dataWithJSONObject:self options:kNilOptions error:&error];
if (error != nil) return nil;
return result;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL: kLatestSearchURL];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
- (void)fetchedData:(NSData *)responseData {
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&error];
// ---------------------------- Will Start Parsing Here ------------------------------
}
#end
God save literals (Xcode 4.5 and iOS 6.0 or later SDK, LLVM Compiler 4.0 required). Deploys back to iOS 5.
NSString *url = resp[#"responseData"][#"results"][0][#"unescapedUrl"];
You can use objectForKey: for dictionaries and objectAtIndex: for arrays:
NSString *url = [[[[resp objectForKey:#"responseData"]
objectForKey:#"results"]
objectAtIndex:0]
objectForKey:#"unescapedUrl"];
I am getting a use of undeclared identifier error in my json but I am following the example from http://blog.zachwaugh.com/post/309924609/how-to-use-json-in-cocoaobjective-c
how do I fix this? Yes I am very new to objective-c \ ios :) Thanks
I am putting this code in my view based application in my viewcontroller.m file
The issue is with "SBJSON *parser = [[SBJSON alloc] init];"
// Create new SBJSON parser object
SBJSON *parser = [[SBJSON alloc] init];
// Prepare URL request to download statuses from Twitter
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://twitter.com/statuses/public_timeline.json"]];
// Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [parser objectWithString:json_string error:nil];
// Each element in statuses is a single status
// represented as a NSDictionary
for (NSDictionary *status in statuses)
{
// You can retrieve individual values using objectForKey on the status NSDictionary
// This will print the tweet and username to the console
NSLog(#"%# - %#", [status objectForKey:#"text"], [[status objectForKey:#"user"] objectForKey:#"screen_name"]);
}
Try changing the line to SBJsonParser *parser = [[SBJsonParser alloc] init];
Edit:
A way that can be easier is to use the NSString category that SBJSON provides:
NSArray *statuses = (NSArray *)[json_string JSONValue];