iOS JSON Parse返回null

时间:2012-11-30 06:34:09

标签: ios xcode json

我已在网上搜索此问题的解决方案,但总是返回给我的结果为空。

这是我从网上收到的以下字符串。一切似乎都很好。但是,当我将此字符串转换为数组时,返回的结果为null。

代码:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"connectionDidFinishLoading");
NSLog(@"Succeeded! Received %d bytes of data",[self.responseData length]);

// String
NSString *responseString = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
NSLog(@"%@", responseString);

NSDictionary *resultsDictionary = [responseString objectFromJSONString];
NSLog(@"%@", resultsDictionary); // Returns null

}

结果:     [{ “CID”: “382595836”, “名称”: “\ u514d \ u7a0e \ u5e97 \ u4e13 \ u5356 \ u54c1”},{ “CID”: “382595837”, “名称”:“\ u9650 \ u91cf \ u7248 \ u9999 \ u6c34 “},{” CID “:” 380837083" , “名”: “\ u5973 \ u58eb \ u7cbe \ u88c5”},{ “CID”: “380837082”, “名”:“\ u7537 \ u58eb \ u7cbe \ u88c5 “},{” CID “:” 61540749" , “名”: “\ u7b80 \ u88c5 \ u5973 \ u7528 \ u9999 \ u6c34”},{ “CID”: “24213689”, “名”:” \ u7b80 \ u88c5 \ u7537 \ u7528 \ u9999 \ u6c34 “},{” CID “:” 25541561" , “名”: “Q \ u9999 \ u5973 \ u58eb”},{ “CID”: “25541841”,“名“:” Q \ u9999 \ u7537 \ u58eb“}]

愿任何人为我提供一种思考方式。

感谢。

3 个答案:

答案 0 :(得分:1)

试试这个

NSMutableData *responseData; //在.h类中使用

在.m类

中使用此函数
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"connection did receive data");
    [responseData appendData:data];
    NSString *responseString = [NSString stringWithUTF8String:[responseData bytes]];
    NSLog(@"%@",responseString);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"Succeeded! Received %d bytes of data", [responseData length]);
}

答案 1 :(得分:0)

使用以下代码。该代码适用于ios 5.0及更高版本。

NSArray* list = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions
                          error:&error];

我这样做了。它对我来说很好。你能尝试低于一个逻辑。

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"demo" ofType:@"json"];
NSData *myData = [NSData dataWithContentsOfFile:filePath];
NSError *error;
id json = [NSJSONSerialization JSONObjectWithData:myData options:kNilOptions error:&error];
NSArray *list = (NSArray *)json;

答案 2 :(得分:-1)

如果您传入的字符串无效,则objectFromJSONString将返回nil

我查了一下

[{"cid":"382595836","name":"\u514d\u7a0e\u5e97\u4e13\u5356\u54c1"},{"cid":"382595837","name":"\u9650\u91cf\u7248\u9999\u6c34"},{"cid":"380837083","name":"\u5973\u58eb\u7cbe\u88c5"},{"cid":"380837082","name":"\u7537\u58eb\u7cbe\u88c5"},{"cid":"61540749","name":"\u7b80\u88c5\u5973\u7528\u9999\u6c34"},{"cid":"24213689","name":"\u7b80\u88c5\u7537\u7528\u9999\u6c34"},{"cid":"25541561","name":"Q\u9999\u5973\u58eb"},{"cid":"25541841","name":"Q\u9999\u7537\u58eb"}] 2012-11-30 14:29:52.779 com.JSON.Product[1979:c07]

JSONLint中的

表示它是无效的JSON