【发布时间】:2015-11-25 08:52:25
【问题描述】:
我们的 iOS ObjectiveC 应用使用的 JSON API 提要有点不稳定,因此有时字段为空。
我们在解析 JSON 时使用
NSDictionary *json = [self JSONFromResponseObject:responseObject];
然后尝试使用带有例如的字段
[widgetIDArray addObject:widget[@"name"][@"id"]];
有时“名称”字段为空。我们:
1) 要求 API 提供者清理其易碎的 API 代码
2) 每次我们尝试使用 json dict 中的内容时检查 null
if ( ![widget[@"name"] isKindOfClass:[NSNull class]] )
3) 使用 try-catch
@try {
[widgetIDArray addObject:widget[@"name"][@"id"]];
}
@catch (NSException *exception)
{
NSLog(@"Exception %@",exception);
}
回答:
感谢您的回答,如下所示。这是我添加的 NSObject 扩展,它允许我获取可能存在或不存在的深度嵌套的 JSON 项。
第一次调用类似
self.item_logo = [self valueFromJSONWithKeyArray:event withKeyArray:@[@"categories",@"bikes",@"wheels",@"model",@"badge_uri"]];
这里是NSObject+extensions.m中的代码
- (id) valueFromJSONWithKeyArray:(id)json withKeyArray:(NSArray *)keyArray
{
for (NSString * keyString in keyArray)
{
if ([json[keyString] isKindOfClass:[NSObject class]])
{
json = json[keyString]; // go down a level
}
else
{
return nil; // we didn't find this key
}
}
return json; // We successfully found all the keys, return the object
}
【问题讨论】:
标签: ios objective-c iphone json