下面的代码仅适用于我的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解析失败:解析数组时的期望值"
你的JSON看起来有问题,
[Message 1,Message 2]
应该 ["Message 1", "Message 2"]
JSON中的"Strings"必须用引号括起来(""
)