简体   繁体   中英

convert Core Data NSManagedObject in to JSON on iPhone?

I was to post some of my COre Data objects back to a web service and would like to send them as JSON. I am receiving objects from the server a JSON using this library:

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

But I cannot figure out how to change my objects back to JSON?

To create json from you r objects, you have to build an NSDictionary from your object, and then convert to 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 as your post request's body.

If you would like a more full-featured solution that what is offered by a standalone parsing library, you may want to take a look at RestKit: http://restkit.org/

The framework wraps the operations of fetching, parsing, and mapping JSON payloads into objects. It also allows you to update remote representations by POST/PUT'ing the objects back with a request. By default, outbound requests are form-encoded but the library ships with a class for using JSON as the wire format for posting back to the server.

At a high level, here's what your fetch & post operations would feel 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 framework takes care of the JSON parsing/encoding on a background thread and let's you declare how attributes in the JSON map to properties on your object. Mapping to Core Data backed classes is fully supported.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM