简体   繁体   English

将Core Data NSManagedObject转换为iPhone上的JSON?

[英]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. 我将一些我的COre Data对象发布回Web服务,并希望将它们作为JSON发送。 I am receiving objects from the server a JSON using this library: 我使用这个库从服务器接收JSON的对象:

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

But I cannot figure out how to change my objects back to JSON? 但我无法弄清楚如何将我的对象更改回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. 要从对象创建json,必须从对象构建NSDictionary ,然后使用SBJsonWriter类转换为字符串。

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/ 如果您想要一个功能更全面的解决方案,即独立解析库提供的解决方案,您可能需要查看RestKit: http: //restkit.org/

The framework wraps the operations of fetching, parsing, and mapping JSON payloads into objects. 该框架包含了获取,解析和将JSON有效负载映射到对象的操作。 It also allows you to update remote representations by POST/PUT'ing the objects back with a request. 它还允许您通过POST / PUT将对象与请求一起更新来更新远程表示。 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. 默认情况下,出站请求是表单编码的,但是库附带了一个类,用于将JSON用作回发到服务器的有线格式。

At a high level, here's what your fetch & post operations would feel like in RestKit: 在较高的层次上,这是您在RestKit中的fetch和post操作的感觉:

- (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. 该框架负责后台线程上的JSON解析/编码,让您声明JSON中的属性如何映射到对象的属性。 Mapping to Core Data backed classes is fully supported. 完全支持映射到Core Data支持的类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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