Dealing with Unicode characters in NSArray after parsing a JSON feed - ios

I've googled this to death and can't find the correct answer. Maybe I'm not phrasing the question correctly. I have a web service that provides a JSON feed. I log in and authenticate my username and password then parse some of the JSON feed and insert it into an NSArray as per below.
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
self.urlData = [[NSMutableData alloc] init];
NSLog(#"DID RECEIVE RESPONSE");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
{
//NSLog(#"THE RAW DATA IS %#", data);
[self.urlData appendData:data];
//NSData
NSString *strRes = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
//NSLog(#"LOGGING THE DATA STRING %#", strRes);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *jsonParsingError = nil;
self.parsedJSONFeed = [NSJSONSerialization JSONObjectWithData:self.urlData options:0 error:&jsonParsingError];
self.titleList = [_parsedJSONFeed valueForKeyPath:#"response.page_items.title"];
self.dateList = [_parsedJSONFeed valueForKeyPath:#"response.page_items.date"];
//NSLog(#"RESPONSE: %#",[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding]);
if (jsonParsingError) {
NSLog(#"JSON ERROR: %#", [jsonParsingError localizedDescription]);
} else {
//NSLog(#"PARSED OBJECT %#", parsedObject);
//NSLog(#"OBJECT: %#", [object class]);
}
[self.tableView reloadData];
}
So now "self.titleList" is an NSArray that contains text but the unicode characters have also passed through from the JSON feed. Is there a way to prevent this happening, or convert those unicode characters before/after parsing the JSON feed? Thanks in advance.

So in case anybody lands on this page with the same problem. In fact, they were HTML encoded unicode entities that were causing the problem.
Import this: https://github.com/Koolistov/NSString-HTML category into your project and send your NSString's to the relevant method. All working fine here now.

Related

Error Store NSdata to NsDictonary

plz help me to parse JSON data. we get response in NSMutable Data. but we cn't take out data in Dictionary. my jsonDictionary get nil.
this is my Url . i have check on JSON Validator.They show Valid Json output. help....
http://mobileapp.merucabs.com/NearByCab_ETA/GetNearByCabs.svc/rest/nearby?Lat=23.0768222&Lng=72.645732&SuggestedRadiusMeters=5000&CabMaxCount=10
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
// NSString *responseString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
//NSLog(#"Response String is %#",responseString);
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
jsonDictionary=[NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableContainers error:nil];
jsonArr=[jsonDictionary objectForKey:#"results"];
// NSLog(#"JSONDictionary is %#",jsonDictionary);
[_categoryListTableView reloadData];
}
I got the output from your URL and I created the New project and Run , the project link is attach here
remove the line from the result <stringxmlns="http://schemas.microsoft.com/2003/10/Serialization/">
and try again
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
id jsonDictionary=[NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:nil];
NSLog(#"JSONDictionary is %#", jsonDictionary);
}
Your json service is returning invalid json. If you inspect the source code of that url you will find
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
on the header of the file. Make sure the json validity with some validation tools like jsonlint.com

using json parser how to display php webservices data in UIview

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

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..]}

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