大家好!我只想问我在做什么有什么问题。我正在使用这两天,但我仍然无法做到。它说“无法识别的选择器发送到实例0x748b800”。 我正在做的是解析json返回的值。以下是json返回值的示例:
{
"data": [
{
"name": "John Patola",
"id": "123444432"
},
{
"name": "Joshua Valdez",
"id": "22234567778"
}
]
}
我想将它们存储在一个名为的数组中
NSArray *storage
。
以下是我的代码:
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[self.rData appendData:data];
}
-(void)connection: (NSURLConnection *)connection didFailWithError:(NSError *)error{
[rData release];
[connection release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSString *myVar = [[[NSString alloc] initWithData:rData encoding:NSUTF8StringEncoding] autorelease];
NSArray *storage =[[(NSDictionary *)myVar objectForKey:@"data"]retain]; // this line seems to be the error
NSLog(@"%i", [storage count]);
当我运行此代码时,出现错误“无法识别的选择器发送到实例0x748b800”。你认为我标记的那条线真的会出错吗?我该如何解决?提前谢谢你的帮助。 ; - )
答案 0 :(得分:1)
在项目中添加JSON
工具包。
在viewController.h
文件中声明方法
-(void)JsonParsing:(NSString *)string;
然后导入
#import "SBJSON.h"
#import "JSON.h"
在您的viewController.m
文件和
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.rData appendData:data];
}
-(void)connection: (NSURLConnection *)connection didFailWithError:(NSError *)error
{
[rData release];
[connection release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *theXMLString = [[NSString alloc]initWithBytes:[self.rData mutableBytes] length:[self.rData length] encoding:NSUTF8StringEncoding];
[self JsonParsing:theXMLString];
}
然后在这里解析你的字符串 -
-(void)JsonParsing:(NSString *)string
{
SBJSON *jsonObject = [[SBJSON alloc]init];
NSArray *dataArray = [[NSArray alloc]init];
dataArray = [jsonObject objectWithString:string];
NSLog(@"%d", [dataArray count]);
}
答案 1 :(得分:0)
这样做:
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSError *error = nil;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData: rData options: NSJSONReadingMutableContainers error: &error];
if (!jsonArray) {
NSLog(@"Error parsing JSON data: %@", e);
} else
{
NSArray *arrValues = [jsonDict objectForKey:@"data"];
for(NSDictionary *item in arrValues) {
NSLog(@"Item: %@", item);
}
}