简体   繁体   English

如何将类对象转换为JSON以进行请求?

[英]How do I convert class objects to JSON for request?

I have some sort of data lets say Passengers and inside passenger I have children's array and infant's array, I am just bamboozled and just didn't get any clue to convert list of passengers to JSON . 我有某种数据可以说,乘客和内部乘客我有儿童数组和婴儿数组,我只是bamboo愧,也没有任何线索将乘客列表转换为JSON

In objective-c so far I have seen that we convert class object to NSDictionary by it toDictionary method. 到目前为止,在Objective-C中,我已经看到我们通过将类对象转换为NSDictionary并将其转换为Dictionary方法。

My question is what if we have list of class object.. what's the catch here? 我的问题是,如果我们有类对象的列表,那该怎么办? how we gonna convert that list? 我们将如何转换该列表?

I have NSMutableArray of passengers and inside a passenger object I have NSMutableArray of children and infants. 我有NSMutableArray的乘客,并且在乘客对象内部有NSMutableArray的儿童和婴儿。

How can I convert that list of passengers to Dictionary for request? 如何将那列乘客列表转换为Dictionary以进行请求?

I am new to objective-c, in java we used to serialise and deserialize. 我是Objective-c的新手,在Java中我们曾经进行过序列化和反序列化。

I have already tried converting NSMutableArray to NSDictionary and so on but it seems like it doesn't work at all. 我已经尝试过将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"
}

I do both the toDictionary and fromDictionary inside of a class object. 我在类对象中同时执行toDictionary和fromDictionary。 If an object has nested class objects, they, likewise, need to implement a toDictionary and fromDictionary methods. 如果对象具有嵌套的类对象,则它们同样需要实现toDictionary和fromDictionary方法。 Here is an example of a Claim class that contains an array of Trip classes: 这是一个包含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

And here is the implementation of the Claim class: 这是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

The NSJSONSerialization class can convert NSDictionary to JSON. NSJSONSerialization类可以将NSDictionary转换为JSON。 See https://developer.apple.com/documentation/foundation/nsjsonserialization 参见https://developer.apple.com/documentation/foundation/nsjsonserialization

You can use codable to serialize a Class to JSON string and do the reverse. 您可以使用codable将Class序列化为JSON字符串,然后执行相反的操作。 Thought the example in Swift JSONEncoder can be accessed from Objective-C. 可以从Objective-C访问Swift JSONEncoder示例

How to use Codable protocol in objective c data model class? 如何在目标c数据模型类中使用Codable协议?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM