1

In reading the documentation and sample code for posting objects, I must have missed something relating to serializing entities. It appears possible to send an entity to postObject and expect it to use the supplied mapping to produce JSON and POST it to a server.

I have been able to map and post an object, but the JSON is not coming through well formed.

I have been able to hand parameterize the object and get valid JSON. I'm about to dig into the source-code, but was wondering what I'm missing.

Here's the code and the results I'm seeing. Insight/help is appreciated!

I have the following Managed Object:

@interface TFUser : NSManagedObject

@property (nonatomic, retain) NSString * first_name;
@property (nonatomic, retain) NSString * last_name;

@end

I have the following code to map it:

+(RKEntityMapping *) mapping
{
  if (_mapping == nil)
  {
    RKObjectManager *objectManager = [RKObjectManager sharedManager];
    assert(objectManager && "Object manager not initialized!?");

    RKManagedObjectStore *managedObjectStore = objectManager.managedObjectStore;
    assert(objectManager && "No object store!?");

    // USER Entity Map
    _mapping = [RKEntityMapping mappingForEntityForName:@"TFUser"
                                   inManagedObjectStore:managedObjectStore];
    [_mapping addAttributeMappingsFromDictionary:@{
                                                   @"first_name": @"first_name",
                                                   @"last_name": @"last_name"
                                                   }];
    _mapping.identificationAttributes = @[ @"first_name" ];
  }

  return _mapping;
}

I have the following code to test serializing one Managed Object directly:

  TFUser *user = (TFUser*) [self.managedObjectContext insertNewObjectForEntityForName:@"TFUser"];
  user.first_name = @"Mickey";
  user.last_name = @"Mouse";

  NSError *error;
  RKRequestDescriptor *requestDescriptor =
  [RKRequestDescriptor requestDescriptorWithMapping:[TFUser.mapping inverseMapping]
                                        objectClass:[TFUser class]
                                        rootKeyPath:@"user"
                                             method:RKRequestMethodAny];

  NSDictionary *parameters = [RKObjectParameterization parametersWithObject:user
                                                          requestDescriptor:requestDescriptor
                                                                      error:&error];

  NSData *jsonData= [RKMIMETypeSerialization dataFromObject:parameters MIMEType:RKMIMETypeJSON error:&error];
  NSString *message = [[NSString alloc] initWithData:jsonData encoding:NSASCIIStringEncoding];

  NSLog(@"USER JSON:\r\n%@", message);

And this produces what I'd expect:

USER JSON:
{
  "user" : {
    "first_name" : "Mickey",
    "last_name" : "Mouse"
  }
}

When I postObject the Managed Object directly:

  [[RKObjectManager sharedManager] postObject:user
                                         path:@"/user"
                                   parameters:nil
                                      success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
                                        NSLog(@"Success");
                                      }
                                      failure:^(RKObjectRequestOperation *operation, NSError *error) {
                                        NSLog(@"Error");
                                      }];

The server receives:

{ user: { first_name: 'Mickey', last_name: 'Mouse' } }

And the parser complains that it can't process the JSON.

Why am I getting a different result? How can I get the post to produce the correct JSON for the server?

Thanks! - Kevin

5
  • Your test should exactly match the true flow. Turn on trace logging and use Charles to verify what is sent. My initial reaction would be something on the server side causing an issue...
    – Wain
    Apr 4, 2014 at 21:04
  • Well... that was quick. Turns out that the server had some code that was attempting to parse the JSON rather than simply accepting the object. The output that was being generated was a dump from the successfully parsed object itself, not the raw bits from the post. It's been working the whole time... Apr 4, 2014 at 21:14
  • Thank you. I'll leave this code sample up for anyone looking for post examples for RestKit. I had to do some digging when I wanted to work with the ManagedObject and maybe this will help some one. Apr 4, 2014 at 21:17
  • You might want to add an answer and accept it (so people know it isn't still an issue) :-)
    – Wain
    Apr 4, 2014 at 21:18
  • Hmm... can't answer my own question for 8 hours? Okay... it's all typed. I'll submit in 8 hours :-) Apr 4, 2014 at 21:47

1 Answer 1

0

The code has been working the entire time. The debugging and some code on the server was broken.

By carefully inspecting the logging of the body request being sent to the server it was apparent that the JSON was well-formed leaving the client. Here it is:

request.headers={
    Accept = "application/json";
    "Accept-Language" = "en;q=1, fr;q=0.9, de;q=0.8, zh-Hans;q=0.7, zh-Hant;q=0.6, ja;q=0.5";
    "Content-Type" = "application/json; charset=utf-8";
    "User-Agent" = "Treefort/1.0 (iPhone Simulator; iOS 7.0.3; Scale/2.00)";
}
request.body={
  "user" : {
    "first_name" : "Mickey",
    "last_name" : "Mouse"
  }
}

The code on the server was doing this:

            console.log req.body                                                                                                                                              
            request = JSON.parse req.body                                                                                                                                     
            user = request.user                                                                                                                                               

The JSON has already been processed into objects by the time it gets here. This means that the log line is dumping the object to the log, not the text of the received body. The second problem is that there is no reason to be explicitly requesting a JSON parse of the body. It's already been converted to objects.

To fix it I just changed the code to be:

        user = req.body.user

Sometimes it helps to have somebody else say... it should be working. I've been banging my head on this for days. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.