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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With