开发者

Using ObjC RestKit library how to map object to JSON NSString *

I'm using RestKit http://restkit.org for iOS. I have an object and an object map开发者_StackOverflow社区ping defined and can use that to send and receive data with the server. However for my mapped objects I'd like to the -description method to return the JSON mapping for logging to the console.

How to map the object to a string?


The object mapping has now changed substantially as of RestKit ObjectMapping 2.0 in the newer versions of Reskit, and @bradgonesurfing's answer won't work in these newer versions.

You now need to use RKObjectParameterization to perform the object serialization as follows:

RKObjectMapping *itemMapping = [RKObjectMaping mappingForClass:[Item class]];
/* Your object mapping definition for the Item class goes here */

RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:itemMapping.inverseMapping objectClass:[Item class] rootKeyPath:nil method:RKRequestMethodPOST];

NSDictionary *dict = [RKObjectParameterization parametersWithObject:item requestDescriptor:requestDescriptor error:nil];
NSData *jsonData = [RKMIMETypeSerialization dataFromObject:dict MIMEType:RKMIMETypeJSON error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];


I figured out a solution

- (NSString*)description
{
    RKObjectMappingProvider * provider = [RKObjectManager sharedManager].mappingProvider;
    RKObjectMapping* mapping = [provider objectMappingForClass:[self class]];
    RKObjectSerializer * serializer = [RKObjectSerializer serializerWithObject:self mapping:mapping];

    NSError * error;
    return (NSString *)[serializer serializedObjectForMIMEType:RKMIMETypeJSON error: &error];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜