我正在尝试获取一些 json 数据并将其显示为 UILabel 中的文本,但我不断收到应用程序崩溃并出现以下错误 -[__NSCFString objectAtIndex:]: unrecognized selector sent to instance 0x1f8cfff0?
这是我的代码和 json 响应。我在我的日志中看到我从调用中获取了名称,但应用程序轰炸了那个错误。我有 2 个 UILabel 块,其中一个显示 json 响应的文本格式,另一个显示文本中的实际 json 响应。
我正在尝试提取此人的姓名,当 json 返回时,我可以在日志中看到 Bilbo Baggins。
这是我的 json 输出:
{"ProfileID":34,"ProfilePictureID":20,"Name":"Bilbo Baggins","Clients":[{"ClientID":91,"Name":"Fnurky"},{"ClientID":92,"Name":"A different client"},{"ClientID":95,"Name":"Second Community"},{"ClientID":96,"Name":"Britehouse"}]}
和我的代码尝试将其显示为 uilabel 作为文本。
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) //1
#define kLatestKivaLoansURL [NSURL URLWithString: @"http://www.ddproam.co.za/Central/Profile/JSONGetProfileForUser"] //2
#import "JsonViewController.h"
@interface NSDictionary(JSONCategories)
+(NSDictionary*)dictionaryWithContentsOfJSONURLString:(NSString*)urlAddress;
-(NSData*)toJSON;
@end
@implementation NSDictionary(JSONCategories)
+(NSDictionary*)dictionaryWithContentsOfJSONURLString:(NSString*)urlAddress
{
NSData* data = [NSData dataWithContentsOfURL: [NSURL URLWithString: urlAddress] ];
__autoreleasing NSError* error = nil;
id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (error != nil) return nil;
return result;
}
-(NSData*)toJSON
{
NSError* error = nil;
id result = [NSJSONSerialization dataWithJSONObject:self options:kNilOptions error:&error];
if (error != nil) return nil;
return result;
}
@end
@implementation JsonViewController
- (void)viewDidLoad
{
[super viewDidLoad];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL: kLatestKivaLoansURL];
[self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSArray* defineJsonData = [json objectForKey:@"Name"]; //2
NSLog(@"Name: %@", defineJsonData); //3
// 1) Get the latest loan
NSDictionary* loan = [defineJsonData objectAtIndex:0];
// 3) Set the label appropriately
humanReadble.text = [NSString stringWithFormat:@"Hello: %@",
[(NSDictionary*)[loan objectForKey:@"Name"] objectForKey:@"Name"]];
//build an info object and convert to json
NSDictionary* info = [NSDictionary dictionaryWithObjectsAndKeys:
[loan objectForKey:@"Name"],
nil];
//convert object to data
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:info
options:NSJSONWritingPrettyPrinted
error:&error];
//print out the data contents
jsonSummary.text = [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding];
}
@end