以下代码仅在我的JSON数据是一系列整数时才有效,例如: [11,12,13]。我怎么能让它来检索一条消息/短语呢?
- (IBAction)checkmessages:(id)sender
{
responseData = [[NSMutableData data] retain];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"file:///Users/Alex/Desktop/Test.json"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSError *error;
SBJSON *json = [[SBJSON new] autorelease];
NSArray *luckyNumbers = [json objectWithString:responseString error:&error];
[responseString release];
if (luckyNumbers == nil)
label.text = [NSString stringWithFormat:@"JSON parsing failed: %@", [error localizedDescription]];
else {
NSMutableString *text = [NSMutableString stringWithString:@"Latest Message:\n"];
for (int i = 0; i < [luckyNumbers count]; i++)
[text appendFormat:@"%@\n", [luckyNumbers objectAtIndex:i]];
label.text = text;
}
}
编辑: 当我的JSON文件看起来像:[10,11,12],它工作正常,但如果我将其更改为:[消息1,消息2],我得到错误:“JSON解析失败:解析数组时的预期值”
答案 0 :(得分:1)
你的JSON看起来格格不入,
[Message 1,Message 2]
应该是
["Message 1", "Message 2"]
答案 1 :(得分:0)
“字符串”必须用引号括起来(""
)。