Search code examples
iosobjective-ciphonejsonrestkit

RestKit error for a nested object while POSTing to server


I am having a service to which following type of request is to be sent

 {"ClientDetails":{"ChauffeurId":0,"FirstName":"String","LastName":"String","Email":"String","Password":"String","PhoneNumber":"String","Thumbnail":"AA==","PayKey":"String","DeviceKey":"String"},"Token":"String"}

I am using following code to send this request using RestKit mapping as shown, problem is I am getting 'Invalid type in JSON write (Client)' error, not able to figure out what is the error.

    RKObjectMapping *requestMapping = [RKObjectMapping mappingForClass:[Client class]];
    [requestMapping addAttributeMappingsFromDictionary:@{ @"FirstName": @"FirstName", @"LastName": @"LastName",@"Email":@"Email",@"PhoneNumber":@"PhoneNumber",@"Token":@"PayKey",@"Password":@"Password",@"ChauffeurId":@"ChauffeurId",@"Image":@"Thumbnail",@"DeviceToken":@"DeviceKey" }];


    RKObjectMapping *tokenMapping = [RKObjectMapping requestMapping];
    [tokenMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"token" toKeyPath:@"Token"]];
    [tokenMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"client"
                                                                               toKeyPath:@"ClientDetails"
                                                                             withMapping:requestMapping]];

    RKRequestDescriptor *tokenReqDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:tokenMapping
                                                                                   objectClass:[RegClientRequest class]
                                                                                   rootKeyPath:nil method:RKRequestMethodPOST];

   // Register our descriptors with a manager
    RKObjectManager *manager = [RKObjectManager sharedManager];

    [manager addRequestDescriptor:tokenReqDescriptor];

    Client *client = [Client new];
    NewUser *user = [NewUser sharedNewUser];
    client.FirstName = user.strFname;
    client.LastName = user.strLname;
    client.Password = user.strPwd;
    client.PhoneNumber = user.strNum;
    client.Email = user.strEmail;
    client.Token = user.strToken;
    client.DeviceToken = user.strDeviceToken;

    RegClientRequest *regClientRequest = [RegClientRequest new];
    regClientRequest.token = [ServiceUrls token];
    regClientRequest.client = client;

    [manager postObject:regClientRequest path:[ServiceUrls registerUser] parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *result) {   
     }

Solution

  • The problem is you're creating a class specific mapping where you should be using [RKObjectMapping requestMapping or taking the inverseMapping.

    That means that at the moment you're mapping a client to a client and trying to put that resulting client into the JSON (instead of mapping the client to a dictionary).