我正在尝试找到一种方法来正确解析我的 json 数组。我无法找到一个好的解决方案来使用 mantle 解析我的 json 对象。我能够找到有关父子对象的信息,但找不到有关持有无钥匙对象集合的信息。我的代码有效,但这不是一种理想的方式,因为视图控制器文件中有太多与数据相关的代码。如果有人能提出更好的方法,我将不胜感激(这意味着更有条理,这样我就不必使用 for 循环来遍历视图控制器中的每个项目)。
这就是我的 json 的样子(数组中的对象没有键):
[
- {
id: 40,
owner:
{
login: “alex",
id: 9,
name: “alex",
avatar: “url here",
url: "url ",
games_url: "url",
type: "User",
site_admin: false
},
name: “test",
compliant: false,
published: false,
url: “url",
tags_url:"url",
subscribers_url: "url",
cover_url:”url",
type: “Game"
},
{
id: 40,
owner:
- {
login: “alex",
id: 9,
name: “alex",
avatar: “url here",
url: "url ",
games_url: "url",
type: "User",
site_admin: false
},
name: “test",
compliant: false,
published: false,
url: “url",
tags_url:"url",
subscribers_url: "url",
cover_url:”url",
type: “Game"
},
{
more items like this...
}
]
这是代码
restmanager.m
- (void)getUserInfo:(void (^)(NSArray *))successBlock failure:(void (^)(NSError *))failureBlock
{
// gets the data from server via afnetworking and sends it via successblock
}
模型类
abcmodel.h
#import "MTLModel.h"
#import <MTLJSONAdapter.h>
@interface abcmodel : MTLModel <MTLJSONSerializing>
@property (nonatomic, copy, readonly) NSString *name;
@property (nonatomic, copy, readonly) NSURL *coverUrl;
@end
abcmodel.m
#import "abcmodel.h"
#import <NSValueTransformer+MTLPredefinedTransformerAdditions.h>
#import <MTLValueTransformer.h>
@implementation abcmodel
+ (NSDictionary *)JSONKeyPathsByPropertyKey
{
return @{
@"name":@"name",
@"coverUrl":@"coverUrl"
};
}
@end
视图控制器.m
@property ( nonatomic, strong ) NSMutableArray *abcs;
- (void)viewDidLoad
{
[super viewDidLoad];
[restmanager sharedInstance]fetchData:.....]{
abcmodel *abcItem;
for (NSDictionary *abcmodelJSON in responseObject)
{
NSError *error;
abcItem = [MTLJSONAdapter modelOfClass:[abcmodel class]fromJSONDictionary:abcmodelJSON error:&error];
if (abcItem)
{
[self.abcs addObject:abcItem];
}else
{
//log error
}
}
}
}
//然后显示在
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
谢谢你。