Error:JSON unrecognized leading character - iphone

I am implementing SBJSON to fetch the data from web service. My code in "ConnectionDidFinishLoading" is as follows:
NSString *responseString = [[NSString alloc] initWithData:responseData encoding: NSUTF8StringEncoding];
NSLog(#"Response String %#", responseString);
NSDictionary *results = [responseString JSONValue];
NSString *extractUsers = [results objectForKey:#"d"];
NSDictionary *finalResult = [extractUsers JSONValue];
NSLog(#"Final Results : %#",finalResult);
But I got the error msg in my console as follows:
-JSONValue failed. Error trace is: (
"Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Unrecognised leading character\" UserInfo=0x686d010
{NSLocalizedDescription=Unrecognised leading character}" )
I have referred several links on stackoverflow and I also use google to find the answer but I am not able to get the solution
If you have solution then share it with me.
Thanx in advance...

first u have to call the selector.
DownloadManager *mgr= [[DownloadManager alloc] sharedManager:self:#selector(downloadVideos:)];// initialize your class where u write all the methods
[mgr downloadVideos]; // call method where u send request to particular url
[mgr autorelease];
than
-(void)downloadVideos:(NSMutableData*)data{
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *parseDict = (NSDictionary*)[responseString JSONValue];
NSLog(#"%#",parseDict);
}

I just had this problem and it turned out to be that the permissions on the directory used by the web service had been changed.
So browse to the WS or try another means of accessing it to make sure it's up.

Related

How to Convert NSData to NSString

I know this has been asked quite before, and I already followed couple of approaches, but they don't work.
Following is what I already tried:
NSString *newStr = [NSString stringWithUTF8String:[responseData bytes]];
NSString *newStr = [NSString stringWithFormat:#"%.*s", [responseData length], [responseData bytes]];
None of them works. In 1st case, it fills newStr with null. In 2nd, it fills with junk characters. I know from debugger log (po responseData) that I get valid response which is like bbbbbb 00 bbbbbb. [server sends them as byte array]
What to do?
EDIT:
I am receiving this data from http request response - using ASIHTTPRequest library, in case anybody can help on that line.
Try this,
NSData *responseData; [Initialize it]
NSString *receivedDataString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#",receivedDataString);
Please try following code
NSString *string = [[[NSString alloc] initWithData: responseData.bytes encoding:NSUTF8StringEncoding] autorelease];
You can use this code lines
NSString *str=[[NSString alloc] initWithBytes:data1.bytes length:data1.length encoding:NSUTF8StringEncoding];
I am posting this for records sake because I found a duplicate and voting to close this down.
Actually what I am receiving is a stream of bytes represented as hex, and all the answers indicated do not work. Only [NSData description] gave me true data, which is something I can't use because it is intended for debugging.
Finally I tried the solution given here, and I get what I want.
Thanks to all for trying to help out.
NSString *image1Data = [[NSData dataWithData:myData] encodeBase64ForData];
But for this, you have to use NSData+Base64Additions class.
Use following way
NSString *dC_Str = [[NSString alloc] initWithData:decryPtd_data encoding:NSASCIIStringEncoding] ;

Memory leak when parse JSON string using SBJSON

I am using following code to parse JSON and getting memory leak (100%) on line number 2. I don't know what is the problem, can someone help me ?
NSString *response = [request responseString];
NSMutableDictionary *responseJSON = [response JSONValue]; (100% leak)
NSString *tockenString = [responseJSON objectForKey:#"Token"];
NSString *userIDString = [responseJSON objectForKey:#"ID"];
I found the answer. Go to SBJsonParser.m function scanRestOfString and change the line
from
*o = [[NSMutableString alloc] initWithBytes:(char*)c length:len encoding:NSUTF8StringEncoding];
to
*o = [[[NSMutableString alloc] initWithBytes:(char*)c length:len encoding:NSUTF8StringEncoding] autorelease];
SBJsonParser has a like in scanRestOfString/NSMutableString. I reported the bug as well. Thank you all.
Remove those 2 autoreleases. They overrelease the objects.
I've had a similar problem but it turned out the leak was actually higher in the chain of methods, but Instruments was (mistakenly) pointing to this line. Look at the methods that store the results retrieved from this code.

Cast JSON object (NSCFDictionary) to string and parse it

I'm working with facebook connect and trying to handle the JSON object that i'm receiving.
I invoked the requstWithGraphPath method and need to get back a JSON object,
tried to parse it and getting an error:
SBJSON *parser = [[SBJSON new] autorelease];
NSData *data = [[NSData alloc] initWithData:result];
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; -> in this line - "[__NSCFDictionary length]: unrecognized selector sent to instance"
NSArray *events = [parser objectWithString:jsonString];
What's the problem?
Can I get the string in an other way or parse the object differently?
Thanks.
If you are working with the delegate callback
- (void)request:(FBRequest *)request didLoad:(id)result;
the parsing work has been done for you. Traverse the NSDictionary or NSArray to find the data you are looking for. If you are working with the delegate callback
- (void)request:(FBRequest *)request didLoadRawResponse:(NSData *)data;
you should initialize an NSString with the data, and use the category method that SBJSON adds to NSString for creating an id. That is assuming the data is data that constructs a string.
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
id result = [jsonString JSONValue];
Are you sure the error happens on that line, or does it happen on the line above?
If result is an NSDictionary (or CFDictionary, same thing), then it is already parsed and you do not need to do that yourself — and it could cause that error message too, on the line above.
The line:
data = [[NSData alloc] initWithData:result];
is almost certainly not what you want to do, as it is equivalent to
data = [result copy];
assuming that result is an NSData object (or NSMutableData), which I'm guessing it isn't.

iPhone encoding of non latin characters

I am trying to parse a JSON response of a GET request. When the characters, are latin no problem.
However when they are not latin the message doesn't come out correctly. I tried greek and instead of "πανος" i get "& pi; & alpha; & nu; & omicron; & sigmaf;"
The code I use for parsing the response is:
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"response %#", responseString);
// array from the JSON string
NSArray *results = [responseString JSONValue];
When I try to read the response from a website using ajax, everything is fine. The same applies when trying to send a GET request to the application servers with data from iphone. So when i transmit data to the server and read it from the website everything is fine. When i try to show the same data in the app, "Houston we have a problem".
Any clues?
EDIT: To avoid misunderstandings, it's not an issue of HTML, I just point out that for some readon utf-8 characters here are encoded correctly and automatically eg. "&pi" will be converted to "π", however objective c doesn't seem to do this on its own
There is a confusion I think.
π is an HTML entity which is unrelated to text encoding like UTF8 / Latin.
Read wikipedia for details about...
You need a parser to decode these entities like the one previously mentioned by Chiefly Izzy:
NSString+HTML category and method stringByReplacingHTMLEntities
Look at Cocoanetics NSString+HTML category and method stringByReplacingHTMLEntities method. You can find it at:
https://github.com/Cocoanetics/NSAttributedString-Additions-for-HTML/blob/master/Classes/NSString%2BHTML.m
Here's a pretty decent list of lot of HTML entities and their corresponding unicode characters.
Try to use this snippet of code:
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSString *decodedString = [NSString stringWithUTF8String:[responseString cStringUsingEncoding:[NSString defaultCStringEncoding]]];
NSLog(#"response %#", decodedString);
// array from the JSON string
NSArray *results = [decodedString JSONValue];
I have faced the same problem, but I solved it by changing the JSON parser. I have started using the SBJSONParser, and now I am getting the appropriate results. This is the code snippet, I have used
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
SBJSON *parser=[[SBJSON alloc]init];
NSArray *JSONData = (NSArray*)[parser objectWithString:returnString error:nil];

How can I parse a longer JSON file than a NSString?

I'm a bit stuck in a project.
I was writing some code to get a JSON file and store it in an NSString before parsing it into a NSArray.
But I get an error:
2010-10-27 20:59:44.813 GeraldKervyn[21752:207] -JSONValue failed. Error trace is: (
"Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Unrecognised leading character\" UserInfo=0x7637890 {NSLocalizedDescription=Unrecognised leading character}"
I think the problem is related to the limited value that an NSString can take.
BTW this is the feed I'm using : http://www.geraldkervyn.com/api/get_recent_posts/
What would be the most convenient way to parse this into an NSArray ?
Thanks !
First, Add the SBJson code to your project, courtesy of Stig Brautaset. Then do this...
NSString *subject = #"http://www.geraldkervyn.com/api/get_recent_posts/";
NSString *encodedSubject =
[subject stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *test = [NSString stringWithContentsOfURL:[NSURL URLWithString:encodedSubject]];
SBJsonParser *parser = [[SBJsonParser new] autorelease];
NSDictionary *json = [parser objectWithString:test];
NSArray *values = [json objectForKey:#"posts"];