我正在尝试从iGoogle计算器获得汇率。我已成功运行NSURLConnection并通过以下方式在NSData中构建结果:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Add the data to our complete response
[urlResponse appendData:data];
}
我现在正在解析google返回的JSON:
- (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 );
我在NSString上使用SBJSON类来解析JSON。我的日志输出如下:
URL: http://www.google.com/ig/calculator?hl=en&q=1USD=?CRC
Result {lhs: "1 U.S. dollar",rhs: "501.756147 Costa Rican colones",error: "",icc: true}
-JSONValue failed. Error is: Illegal start of token [l]
我根本看不出JSON字符串有什么问题。围绕这个问题的其他答案都没有反映出我遇到的问题。
答案 0 :(得分:3)
这不是有效的JSON字符串,因为所有字符串都必须在双引号内。例如,
lhs
应该是
"lhs"
代替。这同样适用于rhs
,error
和icc
。
像往常一样,http://jsonlint.com是检查JSON字符串是否有效的有用资源。
答案 1 :(得分:0)
我同意巴伐利亚。 我使用SBJSON时遇到了同样的错误。
如果是:
{"lhs": "1 U.S. dollar","rhs": "501.756147 Costa Rican colones","error": "","icc": "true"}
你没有问题,但由于json是由谷歌生成的,你必须用双引号括起每个键和值。
这不是您需要的全部内容,但您可以参考此代码:
//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