所以我刚刚开始使用 youtube 数据 API 和 JSONModel。以他们YouTubeBrowserDemo
为出发点:https ://github.com/JSONModel/YouTubeBrowserDemo 。
所以它工作正常,除了有时某些视频的 MediaThumnail 条目没有time
条目。有些返回的视频有,有些没有。我对此很好,当然可以在显示数据时编写简单的检查,但是当arrayOfModelsFromDictionaries
被调用以将返回的 JSON 转换为我的模型时,我收到以下错误,并且如果只有一个 JSON,则没有任何 JSON 被转换(或更多)time
条目丢失:
[JSONModel.m:205] Incoming data was invalid [MediaThumbnail initWithDictionary:]. Keys missing: {(
time
)}
如何使这种转换不是全有或全无的转换?映射时的某种条件检查?或者是否有其他JSONModel
方法已经做到了这一点?
这是 API 调用并尝试转换生成的 JSON:
[JSONHTTPClient getJSONFromURLWithString:searchURL
completion:^(NSDictionary *json, JSONModelError *err) {
//got JSON back
NSLog(@"Got JSON from web: %@", json);
if (err) {
NSLog(@"err = %@",err);
[[[UIAlertView alloc] initWithTitle:@"Error"
message:[err localizedDescription]
delegate:nil
cancelButtonTitle:@"Close"
otherButtonTitles: nil] show];
return;
}
//initialize the models
// THIS IS WHERE IT SOMETIMES RETURNS OBJECTS INTO SELF.OBJECTS IF ALL THE MEDIATHUMBNAILS AHVE TIME ENTRIES, OR NOTHING IF ONE OR MORE ARE MISSING
self.objects = [VideoModel arrayOfModelsFromDictionaries:
json[@"feed"][@"entry"]
];
if (self.objects) {
NSLog(@"Loaded successfully models");
}
这是我的 VideoModel.h 与他们的接近 - 仅添加了一个属性:
@interface VideoModel : JSONModel
@property (strong, nonatomic) NSString* title;
@property (strong, nonatomic) NSArray<VideoLink>* link;
@property (strong, nonatomic) NSArray<MediaThumbnail>* thumbnail;
@property (strong, nonatomic) NSArray<Author>* author;
@end
视频模型.m:
@implementation VideoModel
+(JSONKeyMapper*)keyMapper
{
return [[JSONKeyMapper alloc] initWithDictionary:@{
@"media$group.media$thumbnail":@"thumbnail",
@"title.$t": @"title"
}];
}
@end
还有我的 MediaThumnail.h:
@interface MediaThumbnail : JSONModel
@property (strong, nonatomic) NSURL* url;
@property (assign, nonatomic) int width;
@property (assign, nonatomic) int height;
@property (strong, nonatomic) NSString* time;
@end
媒体缩略图.m:
@implementation MediaThumbnail
@end