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"]];
}
Related
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);
}
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"];
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;
}
I'm trying to create a application that will retrieve JSON data from an HTTP request, send it to a the application main controller as a JSON object then from there do further processing with it.
Where I'm stick is actually creating a class that will serve as a JSON class in which will take a URL, grab the data, and return that object.
Alone, im able to make this class work, however I can not get the class to store the object for my main controller to retrieve it.
Because im fairly new to Objective-C itself, my thoughts are that im messing up within my init call:
-initWithURL:(NSString *) value
{
responseData = [[NSMutableData data] retain];
NSURL *theURL = [NSURL URLWithString:value];
NSURLRequest *request = [NSURLRequest requestWithURL:theURL];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
return self;
}
The processing of the JSON object takes place here:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSError *jsonError;
SBJSON *json = [[SBJSON new] autorelease];
NSDictionary *parsedJSON = [json objectWithString:responseString error:&jsonError];
// NSArray object.
listings = [parsedJSON objectForKey:#"posts"];
NSEnumerator *enumerator = [listings objectEnumerator];
NSDictionary* item;
// to prove that it does work.
while (item = (NSDictionary*)[enumerator nextObject]) {
NSLog(#"posts:id = %#", [item objectForKey:#"id"]);
NSLog(#"posts:address = %#", [item objectForKey:#"address"]);
NSLog(#"posts:lat = %#", [item objectForKey:#"lat"]);
NSLog(#"posts:lng = %#", [item objectForKey:#"lng"]);
}
[responseString release];
}
Now when calling the object within the main controller I have this bit of code in the viewDidLoad method call:
- (void)viewDidLoad {
[super viewDidLoad];
JSON_model *jsonObj = [[JSON_model alloc] initWithURL:#"http://localhost/json/faith_json.php?user=1&format=json"];
NSEnumerator *enumerator = [[jsonObj listings] objectEnumerator];
NSDictionary* item;
//
while (item = (NSDictionary*)[enumerator nextObject]) {
NSLog(#"posts:id = %#", [item objectForKey:#"id"]);
NSLog(#"posts:address = %#", [item objectForKey:#"address"]);
NSLog(#"posts:lat = %#", [item objectForKey:#"lat"]);
NSLog(#"posts:lng = %#", [item objectForKey:#"lng"]);
}
}
take a look at TouchJSON project - http://code.google.com/p/touchcode/wiki/TouchJSON
I think things are happening in the wrong order.
enter viewDidLoad
[JSON_Model initWithURL] is called from viewDidLoad
initWithURL starts fetching data asynchronously.
initWithURL finishes and returns to viewDidLoad.
viewDidLoad continues and displays the empty content of listings
... Time passes whilst the server generates the JSON and returns it.
connectionDidFinishLoading is called once the iPhone recieves the data
connectionDidFinishLoading populates listings with the JSON data.
listings is not access again
the view is never told to refresh once the JSON data has been loaded and parsed.
I found this website to be helpful for using a JSON object in my app.