Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get JSON string for my object with RestKit

I want to create a json string to save in NSUserDefaults and then get it back from it.

I've already added RestKit to my project, to send and receive objects from the server. However, now i want to flatten and save the data.

How do i use restkit to get a JSON string of my object?

like image 966
Lena Bru Avatar asked Oct 02 '22 17:10

Lena Bru


1 Answers

I needed the same functionality (in my case to send he JSON as a multipart attribute), so after a while searching, I get the solution.

You can get the JSON data (and JSON string) using RestKit with that code, you have to pass the object you want to convert, and the mapping you want to use to convert.

RKRequestDescriptor *descriptorObject = ...
Custom *object = ...

NSDictionary *parametersForObject = [RKObjectParameterization parametersWithObject:object requestDescriptor:descriptorObject error:nil];

NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parametersForObject
                    options:NSJSONWritingPrettyPrinted //Pass 0 if you don't care about the readability of the generated string
                    error:&error];

NSString *jsonString;
if (! jsonData) {
    NSLog(@"Got an error: %@", error);
}
else {
    jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

I have not find this documented, I just find it browsing the code, I am not sure if it is a public API or a private one. At least, it works for RestKit 0.20

like image 60
Néstor Avatar answered Oct 05 '22 12:10

Néstor