JSON 到 Objective-C 字典
Posted
技术标签:
【中文标题】JSON 到 Objective-C 字典【英文标题】:JSON to Objective-C Dictionary 【发布时间】:2012-09-16 23:05:42 【问题描述】:我正在向 API 发出 URL 请求,但我不知道如何呈现 JSON,它会生成一个由多个用户组成的数组,例如 ["user": "value", "user":"value"]
,我正在尝试使用 TableView,所以我需要一个 NSDictionary 但我认为最好渲染像users: ["user": "value", "user":"value"]
这样的JSON。我有这个代码来提出请求
#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”
我真的不知道如何做到这一点,所以任何帮助都是有用的,谢谢
【问题讨论】:
【参考方案1】:您收到该错误是因为从“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");
【讨论】:
【参考方案2】:我在想这样的事情
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];
但是对于许多项目来说它看起来效率不高还是我错了?
【讨论】:
以上是关于JSON 到 Objective-C 字典的主要内容,如果未能解决你的问题,请参考以下文章
Objective-C Mantle,反序列化 JSON 字典
AFNetworking 将 JSON 数组发布为多个单条目字典