I am trying to find a way to parse my json array properly. I was unable to figure out a good solution to parse my json object using mantle. I was able to find information on parent child objects but not on holding a collection of keyless objects. My code works but it is not an ideal way since there is too much data related code in view controller file. I would appreciate if someone can suggest a better way of doing this( meaning more organized so that I don't have to use a for loop to go over on each item in view controller ).
This is what my json looks like (no keys for the objects in the array):
[
- {
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...
}
]
this is the code
restmanager.m
- (void)getUserInfo:(void (^)(NSArray *))successBlock failure:(void (^)(NSError *))failureBlock
{
// gets the data from server via afnetworking and sends it via successblock
}
model class
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
viewcontroller.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
}
}
}
}
//and then display it in
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
Thank you.