Search code examples
iosobjective-cdatamodel

Creating a data model from JSON


I have a JSON that looks like this :

{
"club": [
    {
        "titles": "1",
        "league": "epl",
        "country": "england",

    }
}

And I have created a property like this :

@property (strong, nonatomic) NSMutableArray <Clubs> *club;

The club property inherits from the Clubs class which has the titles, leagues and country properties.

When I try to create a dictionary with that data model, I am unable to access the properties inside the club array.

Am I creating the data model incorrectly ?

Creating the dictionary:

        for (NSDictionary *dictionary in responseObject) {

                if (![self.searchText isEqualToString:@""]) {
                    self.predictiveProductsSearch = [[PerdictiveSearch alloc]initWithDictionary:dictionary error:nil];
                    self.predictiveTableView.dataSource = self;
                    [self.predictiveTableView reloadData];
                    self.predictiveTableView.hidden = NO;

            }

        }

Clubs class

 #import <JSONModel/JSONModel.h>


 @protocol Clubs @end
 @interface Clubs : JSONModel

 @property (strong, nonatomic) NSString <Optional> * titles;
 @property (strong, nonatomic) NSString <Optional> * league;
 @property (strong, nonatomic) NSString <Optional> * country;
 @property (strong, nonatomic) NSString <Optional> * topGS;
 @property (strong, nonatomic) NSString <Optional> * GoalSc;
 @property (strong, nonatomic) NSString <Optional> * TransferBudget;


@end

Solution

  • Please use below code to achieve JSON Model saving:

    _club = [[NSMutableArray alloc]init];
    
    NSDictionary *responseObject = @{
        @"club": @[
                 @{
                     @"titles": @"1",
                     @"league": @"epl",
                     @"country": @"england"
    
                 }]
                 };
    NSArray *newResponseObject = [responseObject objectForKey:@"club"];
    for (NSDictionary *dictionary in newResponseObject) {
    
        Clubs *objClubs = [[Clubs alloc]initWithDictionary:dictionary error:nil];
        [_club addObject:objClubs];
    
    }
    
    NSLog(@"%@",[_club objectAtIndex:0]);
    

    which print like below :

    <Clubs> 
       [titles]: 1
       [country]: england
       [GoalSc]: <nil>
       [league]: epl
       [topGS]: <nil>
       [TransferBudget]: <nil>
    </Clubs>