SBJsonParser JSONValue failed. Error is: Illegal start of token
I am trying to get an exchange rate from the iGoogle Calculator. I have successfully run a NSURLConnection and built up the result in an NSData via:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Add the data to our complete response
[urlResponse appendData:data];
}
I am now parsing the JSON returned by google in:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *dataString =[[NSString alloc]initWithData:urlResponse encoding:NSUTF8StringEncoding];
// log out the result
NSLog(@" Result %@", dataString );
NSDictionary *dic = [dataString JSONValue];
NSLog(@" Dic %@", dic );
I am using the SBJSON category on NSString to to parse the JSON. My log output is below:
URL: http://www.google.com/ig/calculator?hl=en&q=1USD=?CRC
Resu开发者_高级运维lt {lhs: "1 U.S. dollar",rhs: "501.756147 Costa Rican colones",error: "",icc: true}
-JSONValue failed. Error is: Illegal start of token [l]
I simply cannot see what is wrong with the JSON string. None of the other answers around this reflect the problem I am having.
That’s not a valid JSON string because all strings must be inside double quotation marks. For example,
lhs
should be
"lhs"
instead. The same applies to rhs
, error
and icc
.
As usual, http://jsonlint.com is a useful resource for checking whether a JSON string is valid or not.
I agree with Bavarious. I had this same error using SBJSON.
if it was:
{"lhs": "1 U.S. dollar","rhs": "501.756147 Costa Rican colones","error": "","icc": "true"}
You'll have no problem but since that json is generated by google you'll have to enclose each key and values with double quotes.
It's not the whole thing you need but you can refer to this code:
//assuming its just a simple json and you already stripped it with { and }
NSString* json = @"asd:\"hello\",dsa:\"yeah\",sda:\"kumusta\"";
//explodes json
NSArray* jsonChunks = [json componentsSeparatedByString:@","];
NSMutableString *trueJson = [[NSMutableString alloc] init];
for (int idx =0; idx < [jsonChunks count]; idx++) {
//explodes each jsonChunks
NSArray *chunky = [[jsonChunks objectAtIndex:idx] componentsSeparatedByString:@":"];
//reconstruction
if (idx+1 == [jsonChunks count]) {
[trueJson appendFormat:@"%@:%@",[NSString stringWithFormat:@"\"%@\"",[chunky objectAtIndex:0]],[chunky objectAtIndex:1]];
}
else {
[trueJson appendFormat:@"%@:%@,",[NSString stringWithFormat:@"\"%@\"",[chunky objectAtIndex:0]],[chunky objectAtIndex:1]];
}
}
NSLog(@"trueJson: %@",trueJson);
//do the realeases yourself Xp
精彩评论