ios - 如何将类对象转换为 JSON 以供请求?

标签 ios objective-c nsmutablearray nsmutabledictionary jsonmodel

我有一些数据可以说乘客和内部乘客我有 child 数组和婴儿数组,我只是被蒙蔽了,只是没有得到任何线索将乘客列表转换为 JSON

到目前为止,在 objective-c 中,我已经看到我们通过 toDictionary 方法将类对象转换为 NSDictionary

我的问题是,如果我们有类对象列表怎么办……这里有什么问题?我们将如何转换该列表?

我有 NSMutableArray 乘客,在乘客对象中我有 NSMutableArray child 和婴儿。

如何将该乘客列表转换为字典以供请求?

我是 objective-c 的新手,在 java 中我们曾经序列化和反序列化。

我已经尝试过将 NSMutableArray 转换为 NSDictionary 等等,但它似乎根本不起作用。

{
   "airline_code":"AA",
   "inbound_trip_id":122222,
   "outbound_trip_id":111111,
   "passengers":[
      {
         "address_line1":"fdsdsf",
         "address_line2":"",
         "children":[
            {
               "city":"abx",
               "country":"abcd",
               "country_access_code":"11",
               "country_code":"AK",
               "date_of_birth":"4#8#2017",
               "email_address":"me@ok.com",
               "first_name":"munna",
               "gender":"Male",
               "inbound_ssr_id":[
                  40420
               ],
               "last_name":"khna",
               "middle_name":"",
               "nationality":"aaaa",
               "outbound_ssr_id":[
                  40417
               ],
               "passport_expiry_date":"4#29#2019",
               "passport_issue_date":"4#8#2019",
               "passport_number":"PPA2345",
               "phone_number":"111111111",
               "state":"aaa",
               "title":"Mr",
               "titleIndex":0,
               "zip_code":"123213"
            }
         ],
         "city":"Dadu",
         "country":"aa",
         "country_access_code":"11",
         "country_code":"aa",
         "date_of_birth":"4#8#1973",
         "email_address":"me@ok.com",
         "firstAdult":0,
         "first_name":"aaa",
         "gender":"Male",
         "inbound_ssr_id":[
            40421
         ],
         "billing_info":false,
         "last_name":"ccc",
         "middle_name":"",
         "nationality":"PK",
         "outbound_ssr_id":[
            40416
         ],
         "passport_expiry_date":"4#29#2019",
         "passport_issue_date":"4#8#2019",
         "passport_number":"PPA12345",
         "phone_number":"111111111",
         "state":"OOA",
         "title":"Mr",
         "zip_code":"324546"
      },
      {
         "address_line1":"dfdsfdsf",
         "address_line2":"",
         "city":"Beletwene",
         "country":"Somalia",
         "country_access_code":"252",
         "country_code":"SO",
         "date_of_birth":"4#8#1989",
         "email_address":"me@me.com",
         "firstAdult":0,
         "first_name":"vv",
         "gender":"Male",
         "genederIndex":0,
         "inbound_ssr_id":[
            40419
         ],
         "billing_info":false,
         "last_name":"fdf",
         "middle_name":"",
         "nationality":"PP",
         "outbound_ssr_id":[
            40418
         ],
         "passport_expiry_date":"4#29#2019",
         "passport_issue_date":"4#8#2019",
         "passport_number":"PPA123435",
         "phone_number":"615100002",
         "state":"PPA",
         "title":"Mr",
         "titleIndex":0,
         "zip_code":"23454"
      }
   ],
   "search_id":"0000000000000000000000000000000000000",
   "token_id":"0000000000000000000000000000000000000"
}

最佳答案

我在类对象内部执行了 toDictionary 和 fromDictionary 操作。如果一个对象有嵌套类对象,它们同样需要实现 toDictionary 和 fromDictionary 方法。以下是包含 Trip 类数组的 Claim 类的示例:

Claim.h

#import <Foundation/Foundation.h>

@interface Claim : NSObject <NSCopying>
{

}

-(id) copy;
-(id) copyWithZone: (NSZone *) zone;

@property (nonatomic, strong) NSNumber *claimID;
@property (nonatomic, strong) NSString *claimantName;
@property (nonatomic, strong) NSNumber *totalAmount;
@property (nonatomic, strong) NSMutableArray *trips;
@property (nonatomic, assign) BOOL isDirty;


-(void) fromDictionary:(NSDictionary *)dict;
-(NSMutableDictionary *) toDictionary;

-(void) getClaim:(NSInteger)claim_id;
-(void) getTrips;

-(BOOL) saveClaim;
-(BOOL) addClaim;
-(BOOL) updateClaim;
-(BOOL) deleteClaim;

@end

这是 Claim 类的实现:

#import "Claim.h"
#import "AppDelegate.h"
#import "Trip.h"

@implementation Claim

@synthesize claimID;
@synthesize claimantName;
@synthesize totalAmount;
@synthesize trips;
@synthesize isDirty;

- (id)init {
    if (self = [super init]) {

        self.claimID = [NSNumber numberWithInteger:0];
        self.claimantName = @"";
        self.totalAmount = [NSNumber numberWithInteger:0];
        self.trips = [[NSMutableArray alloc] init];

        self.isDirty = NO;

    }
    return self;
}

-(id) copy
{

    Claim *newClaim = [[Claim alloc] init];
    newClaim.claimID = [self.claimID copy];
    newClaim.claimantName = [self.claimantName copy];
    newClaim.totalAmount = [self.totalAmount copy];
    newClaim.trips = [[NSMutableArray alloc] initWithArray:self.trips copyItems:YES];

    newClaim.isDirty = self.isDirty;

    return newClaim;
}

-(id) copyWithZone: (NSZone *) zone
{

    Claim *newClaim = [[Claim alloc] init];
    newClaim.claimID = [self.claimID copy];
    newClaim.claimantName = [self.claimantName copy];
    newClaim.totalAmount = [self.totalAmount copy];
    newClaim.adjMiles = [self.adjMiles copy];
    newClaim.trips = [[NSMutableArray alloc] initWithArray:self.trips copyItems:YES];

    newClaim.isDirty = self.isDirty;

    return newClaim;
}


-(NSMutableDictionary *)toDictionary
{

    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    [dict setObject:self.claimID forKey:@"claim_id"];
    [dict setObject:self.claimantName forKey:@"claimant_name"];
    [dict setObject:self.totalAmount forKey:@"total_amount"];

    NSMutableArray *tripArray = [[NSMutableArray alloc] init];

    for (Trip * item in self.trips) {
        NSDictionary *theDict = [item toDictionary];
        [tripArray addObject:theDict];

    }

    [dict setObject:tripArray forKey:@"trips"];

    if (self.isDirty== YES) {
        [dict setValue:@YES forKey:@"is_dirty"];
    } else {
        [dict setValue:@NO forKey:@"is_dirty"];
    }

    return dict;
}

-(void)fromDictionary:(NSDictionary *)dict
{

    self.claimID = [dict objectForKey:@"claim_id"];
    if ([self.claimID isEqual:[NSNull null]]) {
        self.claimID = [NSNumber numberWithInt:0];
    }

    self.claimantName  = [dict objectForKey:@"claimant_name"];
    if ([self.claimantName isEqual:[NSNull null]]) {
        self.claimantName = @"";
    }

    self.totalAmount  = [dict objectForKey:@"total_amount"];
    if ([self.totalAmount isEqual:[NSNull null]]) {
        self.totalAmount = [NSNumber numberWithDouble:0.00];
    }

    self.trips  = [[NSMutableArray alloc] init];

for (NSDictionary *dict in arrayTrips) {
    Trip *item = [[Trip alloc] init];
    [item fromDictionary:dict];
    [self.trips addObject:item];
}

long ruDirty = [[dict valueForKey:@"is_dirty"] integerValue];

if (ruDirty == 1) {
    self.isDirty = YES;
} else {
    self.isDirty = NO;
}

}

- (NSString *)clearNulls:(const char *)value {

    NSString *result;

    if (value == NULL) {
        result = @"";
    } else if (value == nil) {
        result = @"";
    } else {
        result = [[NSString alloc] initWithUTF8String:value];
    }

    return result;
}

-(void)getClaim:(NSInteger)claim_id
{
}


-(void)getTrips
{
}


-(BOOL) saveClaim {

    if ([self.claimID integerValue] == 0) {
        return [self addClaim];
    } else {
        return [self updateClaim];
    }

}

-(BOOL) addClaim {

    return dataSaved;

}

-(BOOL) updateClaim {

    return dataSaved;
}

-(BOOL) deleteClaim {

    return didDelete;

}

@end

关于ios - 如何将类对象转换为 JSON 以供请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55627695/

相关文章:

objective-c - NSString 属性复制还是只读?

ios - NSMutableArray 不返回值并分配给变量

ios - NSString 数组中的重音字符编码不正确

ios - in/dev/fsevents 的 0x3F 0xB3 字节是什么?

ios - Swift 中的 CocoaLumberjack 动态日志记录

iphone - 只有在 Insert-Animation 完成后才重新加载 UITableViewCell

ios - 如何在 Objective-C 中更改 ImageView 的持续时间

ios - Swift - 向 UIWebView ScrollView 添加约束,以便与屏幕边缘的距离始终为 0

objective-c - 核心图图表轴位置

ios - NSStrings 的 NSArray 在一个对象中只返回一个大字符串,我需要很多对象