1

我在网上搜索了解决这个问题的方法,但总是返回给我的结果是空的。

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

编码:

- (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","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" "名称":"Q\u9999\u7537\u58eb"}]

任何人都可以为我提供一个思考这个问题的方法。

谢谢。

4

3 回答 3

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]);
}
于 2012-11-30T06:57:14.390 回答
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;
于 2012-11-30T06:48:11.000 回答
-1

如果您传入的字符串不是有效的 JSON ,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

于 2012-11-30T06:51:44.130 回答