【问题标题】:Creating a data model from JSON从 JSON 创建数据模型
【发布时间】:2023-03-08 10:55:01
【问题描述】:

我有一个如下所示的 JSON:

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

    }
}

我已经创建了一个这样的属性:

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

club 属性继承自具有 Title、League 和 Country 属性的 Clubs 类。

当我尝试使用该数据模型创建字典时,我无法访问俱乐部数组中的属性。

我是否错误地创建了数据模型?

创建字典

        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;

            }

        }

俱乐部课

 #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

【问题讨论】:

  • 首先,为什么需要字典?其次,请在您提到的地方发布代码。
  • @Nitish 我正在尝试将数据存储在字典中,以便可以在 tableView 中将其显示为谓词搜索
  • 显示您的代码,了解如何从 JSON 创建 俱乐部
  • 不相关,但您应该以单数形式命名对象模型,以复数形式命名属性。而Club 很可能是一个类,因此您需要添加另一个星号:@property (strong, nonatomic) NSMutableArray &lt;Club *&gt; *clubs;
  • 能发一下俱乐部班的代码吗?

标签: ios objective-c datamodel


【解决方案1】:

请使用以下代码实现JSON模型保存:

_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]);

打印如下:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    相关资源
    最近更新 更多