Convert NSManagedObject master data to JSON on iPhone?

I had to publish some of my COre Data objects back to the web service and would like to send them as JSON. I get objects from the JSON server using this library:

http://code.google.com/p/json-framework/

But I can not figure out how to change my objects to JSON?

+4
source share
2 answers

To create json from your r objects, you need to build an NSDictionary from your object and then convert to a string with the SBJsonWriter class.

 NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObject:(NSArray *)YourArrayOfElements forKey:@"objects"]; SBJsonWriter *jsonWriter = [SBJsonWriter new]; //Just for error tracing jsonWriter.humanReadable = YES; NSString *json = [jsonWriter stringWithObject:jsonDictionary]; if (!json){ NSLog(@"-JSONRepresentation failed. Error trace is: %@", [jsonWriter errorTrace]); } [jsonWriter release]; NSData *data = [json dataUsingEncoding:NSUTF8StringEncoding]; 

And then you can set the message request body as your body.

+4
source

If you want a more complete solution offered by the stand-alone parsing library, you can take a look at RestKit: http://restkit.org/

The structure wraps the operations of selecting, parsing and mapping useful JSON data into objects. It also allows you to update remote views by POST / PUT'ing objects back with the request. By default, outgoing requests are encoded by forms, but the library comes with a class for using JSON as a wire format for sending to the server.

At a high level, here is what your send and receive operations will look like in RestKit:

 - (void)loadObjects { [[RKObjectManager sharedManager] loadObjectsAtResourcePath:[@"/path/to/stuff.json" delegate:self]; } - (void)objectLoader:(RKObjectLoader*)loader didLoadObjects:(NSArray*)objects { NSLog(@"These are my JSON decoded, mapped objects: %@", objects); // Mutate and PUT the changes back to the server MyObject* anObject = [objects objectAtIndex:0]; anObject.name = @"This is the new name!"; [[RKObjectManager sharedManager] putObject:anObject delegate:self]; } 

The structure takes care of parsing / encoding JSON in the background thread and allows you to declare how the attributes on the JSON map correspond to the properties of your object. Comparison of the main classes supported by the database is fully supported.

+1
source

Source: https://habr.com/ru/post/1340180/


All Articles