how to parse a string in iphone, objective c? - iphone

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];

Related

How to retrieve all country name with counting to NSArray from NSDictionary?

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.

Parsing data from json to iphone application

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);
}

How to parse HTML sub tags in iPhone app?

I have HTML webpage with lot of images and live contents. I need to parse the data from the webpage(HTML) and show in the iPhone app. Am using the following code to parse the HTML content. But i don't know how to parse the sub tags in the tags?
{
NSURL *url = [NSURL URLWithString:#"http://www.samplewebpage.com/vd/t/1/830.html"];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Response : %#", responseString);
NSMutableArray *imageURLArray = [[NSMutableArray alloc] init];
NSMutableArray *divClassArray = [[NSMutableArray alloc] init];
//NSString *regexStr = #"<A HREF=\"([^>]*)\">";
// For image : 1. img src=\"([^>]*)\" 2. <img src=\"([^>]*)\">
// For getting Class div class
NSString *regularExpressString = #"div class=\"([^>]*)\"";
NSError *error;
NSInteger i =0;
while (i<[responseString length])
{
NSRegularExpression *testRegularExpress = [NSRegularExpression regularExpressionWithPattern:regularExpressString options:NSRegularExpressionCaseInsensitive error:&error];
if( testRegularExpress == nil )
{
NSLog( #"Error making regex: %#", error );
}
NSTextCheckingResult *textCheckingResult = [testRegularExpress firstMatchInString:responseString options:0 range:NSMakeRange(i, [responseString length]-i)];
NSRange range = [textCheckingResult rangeAtIndex:1];
if (range.location == 0)
{
break;
}
NSString *classNameString = [responseString substringWithRange:range];
NSLog(#"Div Class Name : %#", classNameString);
[divClassArray addObject:classNameString];
i= range.location;
//NSLog(#"Range.location : %i",range.location);
i=i+range.length;
}
NSLog(#"divClass Array : %#, Count : %d", divClassArray, [divClassArray count]);
}
Response:
<div class="phoneModelItems" style="width:30%;margin-right:4px;">Nokia Model</div>
I want to get the text Nokia Model from the class phoneModelItems. Can you please tell me how to retrieve the text 'Nokia Model'? Thanks in advance.
Here is my Regular Expression for your problem:
<div\sclass=\"phoneModelItems\".*?><a\shref.*?>(.*?)<\/a><\/div>
you can test it on Rubular

retrieve all data of nsarray

I'm using JSON parsing to get data from MySql by using php
I got all data I want, But when I want to print this data I created a for loop but It gives me the last element only .. this is my code
in DidViewLoad:
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *phpUrl = #"http://dt-works.com/eman/bookOwn.php";
NSString *dbName = #"dbName";
NSString *localHost = #"localhost";
NSString *dbUser = #"dbUser";
NSString *dbPwd = #"dbPwd";
int u_id = 1;
NSString *user_id = [NSString stringWithFormat:#"%d",u_id];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:phpUrl]];
[request setHTTPMethod:#"POST"];
NSString *post = [[NSString alloc] initWithFormat:#"dbName=%#&localHost=%#&dbUser=%#&dbPwd=%#&user_id=%#&submit=", dbName, localHost, dbUser, dbPwd, user_id];
[request setHTTPBody:[post dataUsingEncoding:NSUTF8StringEncoding]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSArray *statuses = [parser objectWithString:json_string error:nil];
int arraySize = [statuses count];
for (NSDictionary *status in statuses)
{
bo_id2 = [status objectForKey:#"bo_id"];
bo_name2 = [status objectForKey:#"bo_name"];
bo_au_id2 = [status objectForKey:#"bo_au_id"];
bo_pub_id2 = [status objectForKey:#"bo_pub_id"];
bo_num_pages2 = [status objectForKey:#"bo_num_pages"];
bo_publish_year2 = [status objectForKey:#"bo_publish_year"];
}
NSLog(#"size of array is: %d", arraySize);
for (int i=0; i<arraySize; i++) {
NSLog(#"%d:",i);
// here I want to retrieve all array elements .. when I try
NSLog(#"Book id: %# - book name: %#", bookId, bookName);
// this give me the last elemet only not all data
// I want to get the data here to use it later .. how ???
}
}
any help ??
You appear to just be reassigning the values of each object to an instance variable, an instance variable only points to one object, not all the ones you assign it to.
Most probably you must have been reintializing the array some where. Check that in the entire code.
NSLog(#"Book id: %# - book name: %#", bookId, bookName);
How do you get the bookId and bookName values in the NSLog above? Something missing in your code there.
You can try this :
for(NSDictionary *status in statuses) {
NSLog(#"Book id: %# - Book Name: %#", [status objectForKey:#"bo_id"], [status objectForKey: #"bo_name"]);
}
In other terms, if you want to use a second for loop, go the same way as the first one.
I don't quite understand why you have to use two for loop to finish the task, in your first loop
NSMutableArray *books = [[NSMutableArray alloc] init];
for(NSDictionary *status in statuses){
[books addObject:status];
}
Later when you want to retrieve any books, you can just call [books objectAtIndex:index].
Hopefully this can help.
You should be able to finish all the tasks you asked for.
Edit
If you just want just one element, bo_name for example you can use:
NSMutableArray *books =[[NSMutableArray alloc] init];
for(NSDictionary *status in statuses){
[books addObject:[status objectForKey:#"bo_name"]];
}

Using SBJson, how to retrieve list of strings from array of objects? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Parse JSON in Objective-C with SBJSON
I have below JSON Response (String). I want to parse it into an NSArray with all the patient names.
[{"pat_reg_no":"111181031P1","app_start_time":"10.15","pat_firstname":"Will Smith"},
{"pat_reg_no":"111181031P2","app_start_time":"11.15","pat_firstname":"Shane Watson"},
{"pat_reg_no":"111181031P3","app_start_time":"12.15","pat_firstname":"Michael Hussey"},
{"pat_reg_no":"111181031P1","app_start_time":"10.15","pat_firstname":"Will Smith"}]
How do I parse this?
I write a demo for you.
SBJsonParser *parser = [[SBJsonParser alloc] init];
id jsonObj = [parser objectWithString:#"[{\"pat_reg_no\":\"111181031P1\",\"app_start_time\":\"10.15\",\"pat_firstname\":\"Will Smith\"},{\"pat_reg_no\":\"111181031P2\",\"app_start_time\":\"11.15\",\"pat_firstname\":\"Shane Watson\"},{\"pat_reg_no\":\"111181031P3\",\"app_start_time\":\"12.15\",\"pat_firstname\":\"Michael Hussey\"},{\"pat_reg_no\":\"111181031P1\",\"app_start_time\":\"10.15\",\"pat_firstname\":\"Will Smith\"}]"];
if ([jsonObj isKindOfClass:[NSArray class]]) {
for (id obj in jsonObj) {
if ([obj isKindOfClass:[NSDictionary class]]) {
NSString *name = [obj objectForKey:#"pat_firstname"];
NSLog(#"name %#", name);
}
}
}
[parser release];
Try Below Code.
NSString* jsonString;
//jsonString suppose this String has That JSON Response.
SBJSON *parser = [[[SBJSON alloc] init] autorelease];
NSDictionary *jsonResponse = (NSDictionary*)[parser objectWithString:jsonString error:nil];
NSArray *pat_reg_noArray = [jsonResponse valueForKey:#"pat_reg_no"] ;
NSArray *app_start_timeArray= [jsonResponse valueForKey:#"app_start_time"] ;
NSArray*firstnameArray=[jsonResponse valueForKey:#"pat_firstname"];
I hope It 'll work.
The Array which you have posted belongs to someKey, so do the following
SBJSON *jsonParser = [[SBJSON alloc] init];
NSDictionary * dictionary = [jsonParser objectWithString:YourString];
NSArray * array = [dictionary objectForKey:someKey];
NSMutableArray *nameArray = [NSMutableArray new];
for (NSDictionary *dict in array)
{
[nameArray addObject:[dict objectForKey:#"pat_firstname"];
}
NSLog(#"x is %#",nameArray);
[jsonParser release];
Hope this will solve your problem...
Try this:
NSString *jsonString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSArray* array = [(NSDictionary*)[jsonString JSONValue] objectForKey:#"results"];