检索JSON数据为NSString不是整数?

时间:2011-12-06 20:13:47

标签: iphone xcode json nsstring integer

以下代码仅在我的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解析失败:解析数组时的预期值”

2 个答案:

答案 0 :(得分:1)

你的JSON看起来格格不入,

 [Message 1,Message 2]

应该是

 ["Message 1", "Message 2"]

答案 1 :(得分:0)

<{3}}中的

“字符串”必须用引号括起来("")。