将 JSON 数据检索为 NSString 而不是整数?
仅当我的 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] 时,它工作正常,但如果我将其更改为:[Message 1,Message 2],我收到错误:“JSON 解析失败:解析数组时的预期值”
The code below only works if my JSON data is a series of integers, e.g. [11,12,13]. How could I get it to retrieve a message/phrase instead?
- (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;
}
}
EDIT:
When my JSON File looks like: [10,11,12], it works fine, but if I change it to: [Message 1,Message 2], I get the error: "JSON Parsing Failed: Expected value while parsing array"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的 JSON 看起来格式错误,
应该是
Your JSON looks malformed,
should be
JSON 中的“字符串”必须用引号引起来 (
""
)。"Strings" in JSON must be enclosed in quotes (
""
).