1

我正在向 API 发出 URL 请求,但我不知道如何呈现 JSON,它会生成一个这样的多个用户数组,[{"user": "value"}, {"user":"value"}]我试图使用 TableView,所以我需要一个 NSDictionary,但我认为呈现 JSON 更好喜欢{users: [{"user": "value"}, {"user":"value"}]}。我有这个代码来提出请求

#import "JSONKit.h"
NSError *error = nil;
NSURLResponse *response = nil;
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: @"http://localhost:3000/getusers"]];
[request setHTTPMethod:@"GET"];
NSData *jsonData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
users = [[jsonData objectFromJSONData] objectForKey:@"users"];
usersKeys = [users allKeys];

但我收到了这个错误

2012-09-16 18:51:11.360 tableview[2979:c07]-[JKArray allKeys]:无法识别的选择器发送到实例 0x6d30180 2012-09-16 18:51:11.362 tableview[2979:c07] *由于未捕获而终止应用程序异常“NSInvalidArgumentException”,原因:“-[JKArray allKeys]:无法识别的选择器发送到实例 0x6d30180”

我真的不知道如何做到这一点,所以任何帮助都是有用的,谢谢

4

2 回答 2

2

您收到该错误是因为从“ jsonData”中解析出来的内容不一定是您所期望的(即字典)。

也许您需要在您的代码中进行一些错误检查。

例如:

NSData *jsonData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if(jsonData)
{
    id objectReturnedFromJSON = [jsonData objectFromJSONData];
    if(objectReturnedFromJSON)
    {
        if([objectReturnedFromJSON isKindOfClass:[NSDictonary class]])
        {
            NSDictionary * dictionaryFromJSON = (NSDictionary *)objectReturnedFromJSON;
            // assuming you declared "users" & "usersKeys" in your interface,
            // or somewhere else in this method
            users = [dictionaryFromJSON objectForKey:@"users"];
            if(users)
            {
                usersKeys = [users allKeys];
            } else {
                NSLog( @"no users in the json data");
            }
        } else {
            NSLog( @"no dictionary from the data returned by the server... check the data to see if it's valid JSON");
        }
    } else {
        NSLog( @"nothing valid returned from the server...");
    }
} else {
    NSLog( @"no data back from the server");
}
于 2012-09-16T23:12:44.687 回答
0

我在想这样的事情

NSError *error = nil;
NSURLResponse *response = nil;
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: @"http://localhost:3000/getusers"]];
[request setHTTPMethod:@"GET"];
NSData *jsonData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

JSONDecoder *decoder = [[JSONDecoder alloc]
                        initWithParseOptions:JKParseOptionNone];
NSArray *json = [decoder objectWithData:jsonData];

NSMutableArray *objects = [[NSMutableArray alloc] init];
NSMutableArray *keys = [[NSMutableArray alloc] init];
for (NSDictionary *user in json) {
    [objects addObject:[user objectForKey:@"user" ]];
    [keys addObject:[user objectForKey:@"value" ]];
}
users = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
NSLog(@"users: %@", users);
usersKeys = [users allKeys];

但是对于许多项目来说它看起来效率不高还是我错了?

于 2012-09-16T23:43:38.587 回答