gpt4 book ai didi

ios - 如何使用 JSONModel 创建模型类?

转载 作者:行者123 更新时间:2023-11-28 22:00:29 26 4
gpt4 key购买 nike

我正在尝试使用 JSONModel 创建模型类.使用 NSJSONSerialization 后我的 json 字典如下所示。

      {
apiStatus = {
message = SUCCESS;
success = 1;
};
boardingPoints = "<null>";
inventoryType = 0;
seats = (
{
ac = 0;
available = 1;
bookedBy = "<null>";
commission = "<null>";
fare = 1200;


},
{
ac = 0;
available = 1;
bookedBy = "<null>";
commission = "<null>";
fare = 1200;


},

);
}

JSON 看起来像这样:

   {"boardingPoints":null,"inventoryType":0,"apiStatus":{"success":true,"message":"‌​SUCCESS"},"seats":[{"fare":1200,"commission":null,"bookedBy":null,"ac":false,"ava‌​ilable":true},{"fare":1200,"commission":null,"bookedBy":null,"ac":false,"availabl‌​e":true},]}

我有一个像这样的模型类:-

 @interface Seat : JSONModel

@property (nonatomic,strong)NSString *ac;
@property (nonatomic,strong)NSString *available;
@property(nonatomic,strong)NSString *bookedBy;
@property(nonatomic,strong)NSString *comission;
@property(nonatomic)NSNumber * fare;

对于映射键,我是这样做的:-

 +(JSONKeyMapper*)keyMapper {
return [[JSONKeyMapper alloc] initWithDictionary:@{@"ac":@"ac",
@"available":@"available",
@"bookedBy":@"bookedBy",
@"commission":@"commission",
@"fare":@"fare", }];

}

但是,当我尝试使用此模型时,出现以下错误:

[JSONModel.m:252] Incoming data was invalid [Seat initWithDictionary:]. Keys missing: {(
bookedBy,
comission,
available,
ac,
fare,

)}

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderArray initWithObjects:count:]: attempt to insert nil object from objects[0]'

我是这样使用它的:

 //Using JSON Model.
NSError *jsonError;
seat = [[Seat alloc]initWithDictionary:jsonDictionary error:&jsonError];
jsonArray = @[seat.ac,seat.available,seat.bookedBy,seat.comission,seat.fare];
NSLog(@"JSON Model Array : %@", jsonArray);

如何正确使用?

最佳答案

首先,如果您的属性名称与字段名称匹配,则无需覆盖 +(JSONKeyMapper*)keyMapper。尝试为可以为 null 的字段放置可选关键字。

@interface Seat : JSONModel

@protocol Seat;

@property (nonatomic,strong)NSString *ac;
@property (nonatomic,strong)NSString<Optional> *available;
@property(nonatomic,strong)NSString<Optional> *bookedBy;
@property(nonatomic,strong)NSString *comission;
@property(nonatomic)NSNumber * fare;

@end

更进一步,您可以像这样在顶级类中进行级联:

//Result.h
#import "Seat.h"
#import "APIStatus.h"
@interface Result: JSONModel

@property(nonatomic,strong) APIStatus *apiStatus;
@property(nonatomic,strong) NSString<Optional> *boardingPoints;
@property(nonatomic,strong) NSArray<Seat> *seats;
@property(nonatomic,strong) NSNumber *boardingPoints;

@end

//APIStatus.h
@interface APIStatus: JSONModel

@property(nonatomic,strong) NSString *message;
@property(nonatomic,strong) NSNumber *success;

@end

编辑:这样您只需要使用 JSONModel 初始化结果模型,所有中间类都会自动创建。您可能需要尝试使用属性类型。如果您需要引用,JSONModel 的 github 页面提供了大量解释。

关于ios - 如何使用 JSONModel 创建模型类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25260961/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com