using json parser how to display php webservices data in UIview - ios

i have a PHP webservices. My requirement is using PHP web services to display json data in UIView one by one.
The Json data is :
"id\":\"6\",\"title\":null,\"description\":null,\"year\":\"2012\",\"date\":null}","{\"id\":\"4\",\"title\":\"
correct in the year 2013\",\"description\":\"<\/font> Financial
system in America for this year is not indicated progress this year
too. More problems will creep up. \r\n<\/font> Aggressive stage
of Telangaana agitation- formation of seperate Telangaana state-
bifurcation of state - sure indications are \r\n\r\npredicted.
\r\n*<\/font> The Gujarath CM - Sri Narendra Modi - Bright future
is indicated. \r\n*<\/font> Still danger is indicated for
Indoneshia and Sumitra Islands.
i want to display these data in UIView.Before display each line of data displaying * symbol.How to retrieve and how to display in UIViewcontroller.Help me any body.Thanks in advance.
I am writing like this.but i got exception.
-(void)loadData
{
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
[defaults valueForKey:#"id"];
[defaults valueForKey:#"title"];
[defaults valueForKey:#"description"];
[defaults synchronize];
NSURL *url=[NSURL URLWithString:#"http://www.predictions.php"];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
[[NSURLConnection alloc]initWithRequest:request delegate:self];
urlConnection=[[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
responseData=[[NSMutableData alloc]init];
[responseData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if(connection==urlConnection)
{
strResponse=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#",strResponse);
NSError *error;
jsonDict=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
NSLog(#"%#",jsonDict);
NSArray *arrResults=[jsonDict valueForKey:#"id"];
NSLog(#"%#",arrResults);
arrString=[NSMutableArray array];
for(NSDictionary *dictRes in arrResults)
{
constants *con=[[constants alloc]init];
con.titl=[dictRes valueForKey:#"title"];
// con.desc=[dictRes valueForKey:#"description"];
[arrString addObject:con];
}
[View1 reloadData];
}
}

You can use NSJSONSerialization class for parsing JSON objects.
Hope this helps.

You should use this framework: https://github.com/stig/json-framework and SBJsonParser class to parse the JSON script. The below code will help you parse json response:
SBJSON *parser = [[SBJSON alloc] init] ;
NSDictionary *dic = (NSDictionary *)[parser objectWithString:respString error:nil];
This code will convert your response string in the respString variable into an NSDictionary, and now you can extract each object by calling:
NSString* response = [dic objectForKey:#"response"];

Related

iOS JSON Parse Return null

I have searched online for solution toward this problem, but the result that is always returned to me is null.
This is the following string that I received from a web. Everything seems to work fine. However, when I were to convert this string into an array then the result returned is null.
The code:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"connectionDidFinishLoading");
NSLog(#"Succeeded! Received %d bytes of data",[self.responseData length]);
// String
NSString *responseString = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#", responseString);
NSDictionary *resultsDictionary = [responseString objectFromJSONString];
NSLog(#"%#", resultsDictionary); // Returns null
}
The result:
[{"cid":"382595836","name":"\u514d\u7a0e\u5e97\u4e13\u5356\u54c1"},{"cid":"382595837","name":"\u9650\u91cf\u7248\u9999\u6c34"},{"cid":"380837083","name":"\u5973\u58eb\u7cbe\u88c5"},{"cid":"380837082","name":"\u7537\u58eb\u7cbe\u88c5"},{"cid":"61540749","name":"\u7b80\u88c5\u5973\u7528\u9999\u6c34"},{"cid":"24213689","name":"\u7b80\u88c5\u7537\u7528\u9999\u6c34"},{"cid":"25541561","name":"Q\u9999\u5973\u58eb"},{"cid":"25541841","name":"Q\u9999\u7537\u58eb"}]
May anyone provide me a way to think through this.
Thanks.
try this
NSMutableData *responseData; // use in .h class
use this function in use in .m class
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(#"connection did receive data");
[responseData appendData:data];
NSString *responseString = [NSString stringWithUTF8String:[responseData bytes]];
NSLog(#"%#",responseString);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Succeeded! Received %d bytes of data", [responseData length]);
}
Use below code. The code will work on ios 5.0 and later.
NSArray* list = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions
error:&error];
I did this. It's working fine for me. Can you try below one logic.
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"demo" ofType:#"json"];
NSData *myData = [NSData dataWithContentsOfFile:filePath];
NSError *error;
id json = [NSJSONSerialization JSONObjectWithData:myData options:kNilOptions error:&error];
NSArray *list = (NSArray *)json;
The objectFromJSONString will return nil if the string you're passing in isn't valid JSON.
I checked this
[{"cid":"382595836","name":"\u514d\u7a0e\u5e97\u4e13\u5356\u54c1"},{"cid":"382595837","name":"\u9650\u91cf\u7248\u9999\u6c34"},{"cid":"380837083","name":"\u5973\u58eb\u7cbe\u88c5"},{"cid":"380837082","name":"\u7537\u58eb\u7cbe\u88c5"},{"cid":"61540749","name":"\u7b80\u88c5\u5973\u7528\u9999\u6c34"},{"cid":"24213689","name":"\u7b80\u88c5\u7537\u7528\u9999\u6c34"},{"cid":"25541561","name":"Q\u9999\u5973\u58eb"},{"cid":"25541841","name":"Q\u9999\u7537\u58eb"}] 2012-11-30 14:29:52.779 com.JSON.Product[1979:c07]
in JSONLint it shows it is an invalid JSON.

objectFromJSONString in JSONKit.h returns null in iOS

Please do the following to reproduce the problem
NSString *url = #"http://qdreams.com/laura/index.php?request=EventWeekListings&year=2012&month=10&day=22";
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#" , json);
NSDictionary *deserializedData = [json objectFromJSONString];
deserializedData would contain nil. Expected behavior is to return proper dictionary.
Is that because total number of JSON dictionary elements exceed a certain threshold?
I would appreciate any help in this matter.
Why not just use the NSJSONSerialization method JSONObjectWithData:options:error: it worked fine for me.
NSString *url = #"http://qdreams.com/laura/index.php?request=EventWeekListings&year=2012&month=10&day=22";
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
NSArray *arr = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(#"%#",arr);
After Edit: I ran the code again this morning, and like you I got null. The problem with dataWithContentsOfURL. is that you have no control and no way to know what happened if something went wrong. So, I retested with the code below:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
[self loadData];
}
-(void) loadData {
NSLog(#"loadData...");
self.receivedData = [[NSMutableData alloc] init];
NSURL *url = [NSURL URLWithString:#"http://qdreams.com/laura/index.php?request=EventWeekListings&year=2012&month=10&day=22"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 10.0];
[NSURLConnection connectionWithRequest:request delegate:self];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"didReceiveResponse...");
[self.receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(#"didReceiveData...");
NSLog(#"Succeeded! Received %ld bytes of data",[data length]);
[self.receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"didFailWithError...");
NSLog(#"Connection failed! Error - %# %#",[error localizedDescription],[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
//lblError.text = [NSString stringWithFormat:#"Connection failed! Error - %#",[error localizedDescription]];
self.receivedData = nil;
}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"connectionDidFinishLoading...");
NSError *error = nil;
id result = [NSJSONSerialization JSONObjectWithData:self.receivedData options:kNilOptions error:&error];
if (error) {
NSLog(#"%#",error.localizedDescription);
NSLog(#"%#",[[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding]);
}else{
NSLog(#"Finished...Download/Parsing successful");
if ([result isKindOfClass:[NSArray class]])
NSLog(#"%#",result);
}
}
There was an error, and the log of error.localizesDescription was: "The data couldn’t be read because it has been corrupted". So, it appears that there is something wrong with what's coming back from the server which prevents the JSON parser from working correctly. I also printed out the string along with the error message. Maybe you can look at it carefully and try to figure out what's wrong with the data.
looking at your json you start with the array value (using square brackets) without a name. try reformatting you response with something like this:
{"results":[...the rest of your response..]}

connectionDidFinishLoading is notified before my service is finished

I have data returned from a service that is rendered to my UITableView several times. I moved placed the code that populates my table in the connectionDidFinishLoading delegate. Is this the correct placement of that code?
I have a NSMutableData* receivedData; at the top of my .m file and I have implemented the correct delegates and overridden the correct methods.
I just want to know what I am missing here or what I can do to only see the data from my JSON once in the table view.
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[receivedData setLength:0];
NSLog(#"%#",response);}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(#"Succeeded! Received %d bytes of data",[data length]);
receivedData = [[NSMutableData alloc] init];
[receivedData appendData:data];}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection {
NSError *error = nil;
// Get the JSON data from the website
id result = [NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:&error];
if ([result isKindOfClass:[NSArray class]]) {
for (NSArray *item in result) {
NSArray *category = [item valueForKey:#"CategoryName"];
[dataArray addObject:category];
}
}
else {
NSDictionary *jsonDictionary = (NSDictionary *)result;
for(NSDictionary *item in jsonDictionary)
NSLog(#"Item: %#", item);
}
[self.tableView reloadData];
NSLog(#"Finished");}
I believe you have a line with an error
receivedData = [[NSMutableData alloc] init];
Every time you receive the data you are initializing your object again.
I do recommend this page http://nsscreencast.com/episodes/6-afnetworking for your JSON part.

How to decode route points from the JSON Output Data?

I am new in the ios field, Now i am trying to implement MKMapView Based iPhone Application. From the Google Map Web web service i Fetch the Data in JSON Output Format.
- (void)update {
self.responseData=[NSMutableData data];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://maps.googleapis.com/maps/api/directions/json?origin=Ernakulam&destination=Kanyakumari&mode=driving&sensor=false"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
[self.responseData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[self.responseData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
[connection release];
self.responseData =nil;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(#"connection established");
[connection release];
NSString *responseString=[[NSString alloc]initWithData:self.responseData encoding:NSUTF8StringEncoding];
self.responseData=nil;
NSLog(#" OUTPUT JSON DATA^^^^^^^^^^^^^^^^%#",responseString);
}
I got the out put has in the JSON Format. Now i want to draw route between this two location. sow how can i separate all the latitude and Longitude points from the JSON out put Data.
Check out this code. I am using JSONkit for parsing
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(#"connection established");
[connection release];
NSString *responseString=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSMutableDictionary *data1 = [responseData objectFromJSONData];
NSMutableArray *ad = [data1 objectForKey:#"routes"];
NSMutableArray *data2 = [[ad objectAtIndex:0] objectForKey:#"legs"];
NSMutableArray *data3 = [[data2 objectAtIndex:0] objectForKey:#"steps"];
// NSLog(#"Data3 %#", data3);
for(int i = 0; i<data3.count;i++){
NSLog(#"Start %#", [[data3 objectAtIndex:i] objectForKey:#"start_location"]);
NSLog(#"End %#", [[data3 objectAtIndex:i] objectForKey:#"end_location"]);
}
}
I am using SBJson to parse json data.
In general, call [responseString JSONValue] to get parsed data.
You can google it for detail reference.

iphone json twitter web service question

Im using json to load a table in my app from a twitter web service,
it works fine when using the search function,
http://search.twitter.com/search.json?q=mobtuts&rpp=5
the type of json response for the first one is: tenga: {"completed_in" = "0.076"; ...
but when I use the statuses function,
[NSURL URLWithString:#"http://twitter.com/statuses/user_timeline.json?id=hypercomputing"]];
the type of json response for the second one is: tenga: (
{
contributors = "<null>";
coordinates = "<null>";
"created_at" = "Thu Aug 04 23:26:05 +0000 2011";...
the result from json is different, so my app doesnt see the second call as a dictionary once imported from json, it sees it as a string, [because of the "(" ??]
here the code
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
responseData = [[NSMutableData data] retain];
tweets = [NSMutableArray array];
NSURLRequest *request = [NSURLRequest requestWithURL:
// [NSURL URLWithString:#"http://twitter.com/statuses/user_timeline.json?id=hypercomputing"]];
[NSURL URLWithString:#"http://search.twitter.com/search.json?q=mobtuts&rpp=5"]];// hypercomputing
//[NSURL URLWithString:#"http://twitter.com/statuses/public_timeline.json?id=hypercomputing"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
return YES;
}
#pragma mark NSURLConnection delegate methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSLog(#"string: %#",responseString);
NSDictionary *results = [responseString JSONValue];
NSLog(#"tenga: %#",results);
//NSLog(#"tenga: %#",[results objectForKey:#"("] );
//NSArray * keys = [results allKeys]; //ensa
//NSLog(#"keys: %#",keys); //ensayo
NSArray *allTweets = [results objectForKey:#"results"];
//NSArray *allTweets = [results objectForKey:#"user"];
NSLog(#"user is: %#",allTweets);
//[viewController setTweets:allTweets];
[window addSubview:viewController.view];
[window makeKeyAndVisible];
}
so how can I make sure to receive a dictionary from the json call?,
thanks a lot!
Instead of expecting a dictionary every time, considering testing the class of the incoming JSON object and writing code that handles each case.
Or, more to your point, write an intermediary web service to massage the JSON into something your app can recognize.
Since you're working with defined APIs offered by Twitter, you'll have to read up on the documentation to know what to expect and adjust your implementation accordingly. This isn't a case where you can change the data to meet your needs, you have to change the handling of the data.

Resources