[英]convert Core Data NSManagedObject in to JSON on iPhone?
我将一些我的COre Data对象发布回Web服务,并希望将它们作为JSON发送。 我使用这个库从服务器接收JSON的对象:
http://code.google.com/p/json-framework/
但我无法弄清楚如何将我的对象更改回JSON?
要从对象创建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];
然后你可以设置为你的帖子请求的正文。
如果您想要一个功能更全面的解决方案,即独立解析库提供的解决方案,您可能需要查看RestKit: http: //restkit.org/
该框架包含了获取,解析和将JSON有效负载映射到对象的操作。 它还允许您通过POST / PUT将对象与请求一起更新来更新远程表示。 默认情况下,出站请求是表单编码的,但是库附带了一个类,用于将JSON用作回发到服务器的有线格式。
在较高的层次上,这是您在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];
}
该框架负责后台线程上的JSON解析/编码,让您声明JSON中的属性如何映射到对象的属性。 完全支持映射到Core Data支持的类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.