I am parsing data from iphone app to json from server but it does not get data from the json
i am using following code
To get Data from json
here is the link of my json data
http://celeritas-solutions.com/emrapp/surveyDescription.php?user_id=ali40
NSString*user=#"ali40";
NSString *url=[NSString stringWithFormat:#"http://celeritas-solutions.com/emrapp/surveyDescription.php?user_id=%#",user];
NSLog(url);
NSArray *tempArray =[[DataManager staticVersion] startParsing:url];
for (int i = 0; i<[tempArray count]; i++) {
id *item = [tempArray objectAtIndex:i];
NSDictionary *dict = (NSDictionary *) item;
ObjectData *theObject =[[ObjectData alloc] init];
[theObject setUser_id:[dict objectForKey:#"user_id"]];
[theObject setSurvey_id:[dict objectForKey:#"survey_id"]];
[theObject setSurvey_title:[dict objectForKey:#"survey_Title"]];
[theObject setSurvey_Description:[dict objectForKey:#"survey_Description"]];
[theObject setDate_Created:[dict objectForKey:#"date_Created"]];
[surveyList addObject:theObject];
[theObject release];
theObject=nil;
int count =[surveyList count];
NSLog(#"Total is %d",count);
DataManager Class
DataManager *theInstance;
+ (id)staticVersion{
if(!theInstance){
theInstance = [[DataManager alloc] init];
}
return theInstance;
}
- (NSMutableArray *) startParsing:(NSString *)theURLString {
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#",theURLString]];
NSString *fileContent= [NSString stringWithContentsOfURL:url];
SBJSON *parser = [[SBJSON alloc] init];
NSDictionary *data = (NSDictionary *) [parser objectWithString:fileContent error:nil];
NSArray *items = (NSArray *) data ;
return items;
int count=[items count];
NSLog(#"This is testing %d",count);
}
You json is not correct.
It should be like this:
{"ali40":[{"user_id":"ali40","survey_id":"1","survey_title":"Resturant Survey","survey_description":"Survey To get feedback from clients about food quality and any suggestion to improve the service","date_created":"2012-07-24 22:39:14","color":"[UIColor GrayColor]"},{"user_id":"ali40","survey_id":"2","survey_title":"Travel Servey","survey_description":"Toursim Survey","date_created":"2012-07-25 00:43:42","color":"[UIColor greyColor]"}]}
This code returns not null result
NSString*user=#"ali40";
NSString *url=[NSString stringWithFormat:#"http://celeritas-solutions.com/emrapp/surveyDescription.php?user_id=%#",user];
NSLog(#"%#",url);
NSData* data = [NSData dataWithContentsOfURL:
[NSURL URLWithString: url]];
__autoreleasing NSError* error = nil;
id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (error != nil) NSLog(#"%#",error);
NSLog(#"%#",result);
Output:
2012-07-26 10:26:22.226 test[2511:f803] (
{
color = "[UIColor GrayColor]";
"date_created" = "2012-07-24 22:39:14";
"survey_description" = "Survey To get feedback from clients about food quality and any suggestion to improve the service";
"survey_id" = 1;
"survey_title" = "Resturant Survey";
"user_id" = ali40;
},
{
color = "[UIColor greyColor]";
"date_created" = "2012-07-25 00:43:42";
"survey_description" = "Toursim Survey";
"survey_id" = 2;
"survey_title" = "Travel Servey";
"user_id" = ali40;
}
)
If you json returns many records you need modify your json file
{"users":[{"user_id":"ali40","survey_id":"1","survey_title":"Resturant Survey","survey_description":"Survey To get feedback from clients about food quality and any suggestion to improve the service","date_created":"2012-07-24 22:39:14","color":"[UIColor GrayColor]"},{"user_id":"ali40","survey_id":"2","survey_title":"Travel Servey","survey_description":"Toursim Survey","date_created":"2012-07-25 00:43:42","color":"[UIColor greyColor]"}]}
Then you get the array of records:
NSArray *allItems = [result objectForKey:#"users"];
for (int i=0; i<allItems.count; ++i) {
NSDictionary *item = [allItems objectAtIndex:i]; //here you get every user
NSString *user_id=[item objectForKey:#"user_id"];
NSLog(#"user_id %#",user_id);
}
Related
Here is my dictionary result.
"continent_code" = EU;
"country_code" = gb;
"country_id" = 169;
"country_name" = "United Kingdom";
NSString *responseString = [[NSString alloc] initWithData:responseData
encoding:NSUTF8StringEncoding];
NSDictionary *LoginResult = (NSDictionary*)[responseString JSONValue];
I want to retrieve only country name to NSArray from dictionary.
Try This ::
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:webData options:NSJSONReadingMutableContainers error:&error];
NSLog(#" Value :: %#", [[jsonArray JSONRepresentation] JSONValue]);
for (NSDictionary *item in jsonArray) {
NSLog(#" Item :::::> %#", [item objectForKey:#"country_name"]);
}
Hope, It'll help you.
NSMutableArray *wholeJsonArray = [LoginResult objectForKey:#"RootName"];
NSMutableArray *loginArray = [[NSMutableArray alloc]init];
for(int i = 0 ; i<[loginArray count];i++)
{
NSString *countryName=[[loginArray objectAtIndex:i]objectForKey:#"country_name"];
[loginArray addObject:countryName];
}
Good luck !!
The Correct Method to fill countryArray :
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:yourResponseData options:kNilOptions error:&error];
NSArray* getMAS_CR = [(NSDictionary*)json objectForKey:#"yourKeyRootResult"];
NSMutableArray *countryArray = [[NSMutableArray alloc]init];
for (NSDictionary *rr in getMAS_CR)
{
NSString *cName = [NSString stringWithFormat:#"%#",[rr objectForKey:#"country_name"]];
[countryArray addObject:cName];
}
NSLog(#"countryArray :: %#",countryArray);
GoodLuck.
Hello I am parsing a RSS And Atom feeds, and my question is how can I check for < img > and < url > tags in < description >?
There must be some sort of check. Thanks.
Here is how I parse them:
- (NSArray *)parseFeed:(NSURL *)feedURL{
NSError *error;
NSData *data = [NSData dataWithContentsOfURL:feedURL];
GDataXMLDocument *xmlParse = [[GDataXMLDocument alloc] initWithData:data error:&error];
GDataXMLElement *rootElement = xmlParse.rootElement;
NSArray *array = [[NSArray alloc] init];
if ([rootElement.name compare:#"rss"] == NSOrderedSame) {
array = [self parseRSSFeed:rootElement];
return array;
} else if ([rootElement.name compare:#"feed"] == NSOrderedSame) {
array = [self parseAtomFeed:rootElement];
return array;
} else {
NSLog(#"Unsupported root element: %#", rootElement.name);
return nil;
}
}
-(NSArray *)parseRSSFeed:(GDataXMLElement *) rootElement
{
NSMutableArray *entries = [[NSMutableArray alloc] init];
NSArray *channels = [rootElement elementsForName:#"channel"];
for (GDataXMLElement *channel in channels) {
NSArray *items = [channel elementsForName:#"item"];
for (GDataXMLElement *item in items) {
FeedItem *itemF = [[FeedItem alloc] init];
itemF.title = [item valueForChild:#"title"];
itemF.description = [item valueForChild:#"description"];
NSLog(#"IMAGE - %#", [item valueForChild:#"img"]);
itemF.dateString = [item valueForChild:#"pubDate"];
itemF.link = [NSURL URLWithString:[item valueForChild:#"link"]];
itemF.dateString = [item valueForChild:#"updated"];
itemF.author = [item valueForChild:#"author"];
[entries addObject:itemF];
NSLog(#"RSS - %#", itemF.title);
}
}
NSArray *RSSArray = [entries copy];
return RSSArray;
}
-(NSArray *)parseAtomFeed:(GDataXMLElement *) rootElement
{
NSMutableArray *entries = [[NSMutableArray alloc] init];
NSArray *entry = [rootElement elementsForName:#"entry"];
for (GDataXMLElement *entryElement in entry) {
// NSArray *items = [channel elementsForName:#"item"];
//for (GDataXMLElement *item in items) {
FeedItem *itemF = [[FeedItem alloc] init];
itemF.title = [entryElement valueForChild:#"title"];
itemF.description = [entryElement valueForChild:#"summary"];
NSArray *links = [entryElement elementsForName:#"link"];
for (GDataXMLElement *link in links) {
itemF.link = [NSURL URLWithString:[[link attributeForName:#"href"] stringValue]];
}
itemF.dateString = [entryElement valueForChild:#"updated"];
NSArray *authors = [entryElement elementsForName:#"author"];
for (GDataXMLElement *authorElement in authors) {
itemF.author = [authorElement valueForChild:#"name"];
}
[entries addObject:itemF];
NSLog(#"Atom - %#", itemF.title);
}
NSArray *atomArray = [entries copy];
return atomArray;
}
I am parsing them using GDataXMLParser, and my own parser class.
Do it like this:
NSString *Str=[item valueForChild:#"description"];
NSArray *tmp=[Str componentsSeparatedByString:#"<Img>"];
if([tmp count]>1){
NSString *urlstr=[[tmp objectatindex:1] stringByReplacingOccurrencesOfString:#" </Img>" withString:#""];
}
Now urlstr contains your image url.
Enjoy
I thought that
itemF.description = [item valueForChild:#"description"];
is NSString. So you can use componentsSeparatedByString with "your tag".
It will return array. In array at postion 1 you will get your img url.
This url has closing bracket "your closing tag".
Replace "your closing tag" with space. You will get image url.
Hope, this will help you.
I have a string in this format :- { panel : {start : [{"element_id" : 0, "element_name" :0, "element_image" : 0, "element_desc" : 0, "element_dob" : 0, "awards" :0},]} how can I parse this string. please help me to overcome this problem. I tried SBJSon - code: -
NSLog(#"response string before = %#", responseStr);
NSData *fileData = [NSData dataWithContentsOfFile:responseStr];
NSString *responseString = [[NSString alloc] initWithData:fileData encoding:NSUTF8StringEncoding];
NSLog(#"response string after = %#", responseString);
NSError *jsonError = nil;
NSDictionary *feed = nil;
SBJsonParser *json = [[SBJsonParser new] autorelease];
feed = [json objectWithString:responseString error:&jsonError];
NSLog(#"feed = %#", feed);
if ([jsonError code]==0) {
// get the array of "results" from the feed and cast to NSArray
NSMutableArray *localObjects = [[[NSMutableArray alloc] init] autorelease];
NSArray *results= (NSArray *)[feed valueForKey:#"start"];
// loop over all the results objects and print their names
int ndx;
for (ndx = 0; ndx < results.count; ndx++)
{
[localObjects addObject:(NSDictionary *)[results objectAtIndex:ndx]];
}
NSLog(#"local objects = %#", localObjects);
}
the NSDictionary feed is getting nil value in NSLog..
Try the following one...
SBJSON *json = [[SBJSON new] autorelease];
NSDictionary *dictResponse = (NSDictionary*) [json objectWithString:sitesResponse error:nil];
You can use Regular Expressions (wiki). Take sources from: RegexKit, add to linker flags "-fopenmp" and use in NSString message "stringByMatching".
For example, if you want take "element_name":
NSString* str = [your_string stringByMatching:#"element_name\".*:(.*?)," capture: 1L];
I am parsing the data it gets all the data in dictionary but when i check value using NSLog it showa nil value
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.krsconnect.no/community/api.html?method=bareListEventsByCategory&appid=620&category-selected=350&counties-selected=Vest-Agder,Aust-Agder"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *object = [parser objectWithString:json_string error:nil];
//appDelegate.books = [[NSMutableArray alloc] initWithCapacity:0];
appDelegate.books1 = [[NSMutableArray alloc] init];
NSArray *results = [parser objectWithString:json_string error:nil];
for (int i=0; i<[results count]; i++) {
Book1 *aBook = [[Book1 alloc] initWithDictionary:[results objectAtIndex:i]];
[appDelegate.books1 addObject:aBook];
Book1 *mybook=[appDelegate.books1 objectAtIndex:i];
NSString*test=mybook.location;
NSLog(test);
}
Dicionary parsing
- (id)initWithDictionary:(NSDictionary*) dict {
self.date = [dict valueForKey:#"date"];
self.location = [dict valueForKey:#"location"];
self.municipality = [dict valueForKey:#"municipality"];
self.title = [dict valueForKey:#"title"];
return self;
}
I'm guessing that your dictionary doesn't contain a "location", and that's consistent with what I see coming back from that web site. It sends back an array of dictionaries which contain arrays of dictionaries. You need to extract one of those inner dictionaries to find a "location".
[
{
"date":1320883200000,
"events":[
{
"affectedDate":1320883200000,
"event":{
"appId":620,
"eventId":20672,
"location":"Samsen Kulturhus",
"municipality":"Kristiansand",
"title":"AKKS kurs høsten 2011"
}
},
....
Try:
- (id)initWithDictionary:(NSDictionary*) dict {
self = [super init];
if(self) {
self.date = [dict valueForKey:#"date"];
self.location = [dict valueForKey:#"location"];
self.municipality = [dict valueForKey:#"municipality"];
self.title = [dict valueForKey:#"title"];
}
return self;
}
-(void) readRestaurantFromXml {
SGAAppDelegate *app = (SGAAppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *myRequestString = [NSString stringWithFormat:#"%#getXml.aspx",app.SERVER_URL];
NSURL *url = [NSURL URLWithString: myRequestString];
CXMLDocument *rssParser = [[[CXMLDocument alloc] initWithContentsOfURL:url options:0 error:nil] autorelease];
resultNodes = [rssParser nodesForXPath:#"//item" error:nil];
listOfItems = [[NSMutableArray alloc] init];
for (CXMLElement *resultElement in resultNodes) {
NSString *theatre_id = [[resultElement childAtIndex:0] stringValue];
NSString *theatre_name = [[resultElement childAtIndex:1] stringValue];
NSString *restaurant_id = [[resultElement childAtIndex:2] stringValue];
NSString *restaurant_name = [[resultElement childAtIndex:3] stringValue];
NSString *restaurant_desc = [[resultElement childAtIndex:4] stringValue];
NSString *deal_avail = [[resultElement childAtIndex:5] stringValue];
NSString *deal_details = [[resultElement childAtIndex:6] stringValue];
Restaurant *workVal = [[Restaurant alloc] initWithRestTitle:restaurant_name restDesc:restaurant_desc theatreId:theatre_id theatreName:theatre_name restId:restaurant_id restDeals:deal_avail restDealDesc:deal_details];
[listOfItems addObject:workVal];
[workVal release];
}
}
-(void)myTask{
NSLog(#"%d",[listOfItems count]);
}
The NSMutableArray listofItems has 3 values.So how can i extract the array value in another method?
Help me
Fast enumeration is the preferred method.
for (id object in listOfItems) {
//Do something...
}
If you want a single object at an index:
id object = [listOfItems objectAtIndex:someIndex];
If you just want an object (expecting the array to have a single object:
id object = [listOfItems lastObject];
for(int i=0; i < [listOfItems count]; ++i) {
Restaurant* r = [listofItems objectAtIndex:i];
}