Answer the question
In order to leave comments, you need to log in
How to parse complex JSON using RestKit?
Good afternoon!
I just started learning iOS and RestKit, so don't kick me :)
You need to parse the following json response using RestKit:
{"response":["60289",{"ID":"15405114","HEADER":"…"}, {"ID":"15405113","HEADER":"…"},{"ID":"15405112","HEADER":"…"}]}
60289 – total number of records in the allocated database.
It is required to get an array of Messages - ID, HEADER, ..
I created two classes:
@interface Agancy : NSObject
@property (nonatomic, assign) long id;
@property (nonatomic, strong) NSString *name;
-(id) initWithDictionary:(NSDictionary*)source {
self = [super init];
if (self) {
self.id = [[source valueForKey@"agancy"] longValue];
self.name = [source valueForKey@"agancy_name"];
}
return self;
}
@interface Message : NSObject
@property (nonatomic, assign) long id;
@property (nonatomic, strong) NSString *header;
@property (nonatomic, strong) Agancy *agancy;
-(id) initWithDictionary:(NSDictionary*)source {
self = [super init];
if (self) {
self.id = [[source valueForKey@"id"] longValue];
self.header = [source valueForKey@"header"];
self.agency = [[Agancy alloc] initWithDictionary:source];
}
return self;
}
-(void) loadMessages {
AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[Message class]];
RKResponseDescriptor *response = [RKResponseDescriptor responseDescriptorWithMapping:mapping
Method:RKRequustMethodGet
pathPattern:@"/messages.get"
keyPath:@"responde"
statusCodes:[NSIndexSet indexSetWithIndex:200]];
[delegate.objectManager addResponseDescriptor response];
[delegate.objectManager getObjectsAtPath:@"/messages.get"
parameters:nil
success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
NSLog(@"success");
} failure:^( RKObjectRequestOperation *operation, NSError *error) {
NSString @msg = [NSString stringWithFormat:@"Ошибка %@", error.localizedDescription];
NSLog(@"%@", msg);
}
];
}
Answer the question
In order to leave comments, you need to log in
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[Message class]];
RKObjectMapping *messageMapping = [RKObjectMapping mappingForClass:[Message class]];
[messageMapping addAttributeMappingsFromDictionary:@{ @"ID": @"id", @"HEADER" : @"header" }];
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question