簡體   English   中英

將Core Data NSManagedObject轉換為iPhone上的JSON?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM