JSON e Core Data no iPhone

Eu tenho um gráfico de object de core data (composto por duas entidades ligadas por um relacionamento para muitos).

Fiquei curioso, como um desenvolvedor de iPhone relativamente inexperiente, se alguém poderia recomendar uma abordagem, e uma implementação JSON adequada para o iPhone, o que me permitiria:

  1. converter os registros de core data em uma string JSON (mantendo a relação entre as entidades); e

  2. converta a string JSON de volta em objects de dados principais (preservando novamente o relacionamento entre as entidades).

Eu procurei, sem sucesso, por um exemplo de tutorial / código neste ponto para que qualquer assistência seja recebida com gratidão.

Primeiro, escolha uma biblioteca JSON para usar, eu pessoalmente gosto do TouchJSON, mas vários outros por aí são bem legais também. A parte complicada, embora não muito difícil, é converter seus objects gerenciados em estruturas adequadas para a conversão. Eu escrevi isso bem rápido, então pode ter um erro ou dois 🙂

Os methods que você chama são:

 - (NSString*)jsonStructureFromManagedObjects:(NSArray*)managedObjects; - (NSArray*)managedObjectsFromJSONStructure:(NSString*)json withManagedObjectContext:(NSManagedObjectContext*)moc; 

E a implementação é a seguinte:

 - (NSDictionary*)dataStructureFromManagedObject:(NSManagedObject*)managedObject { NSDictionary *attributesByName = [[managedObject entity] attributesByName]; NSDictionary *relationshipsByName = [[managedObject entity] relationshipsByName]; NSMutableDictionary *valuesDictionary = [[managedObject dictionaryWithValuesForKeys:[attributesByName allKeys]] mutableCopy]; [valuesDictionary setObject:[[managedObject entity] name] forKey:@"ManagedObjectName"]; for (NSString *relationshipName in [relationshipsByName allKeys]) { NSRelationshipDescription *description = [[[managedObject entity] relationshipsByName] objectForKey:relationshipName]; if (![description isToMany]) { NSManagedObject *relationshipObject = [managedObject valueForKey:relationshipName]; [valuesDictionary setObject:[self dataStructureForManagedObject:relationshipObject] forKey:relationshipName]; continue; } NSSet *relationshipObjects = [managedObject objectForKey:relationshipName]; NSMutableArray *relationshipArray = [[NSMutableArray alloc] init]; for (NSManagedObject *relationshipObject in relationshipObjects) { [relationshipArray addObject:[self dataStructureForManagedObject:relationshipObject]]; } [valuesDictionary setObject:relationshipArray forKey:relationshipName]; } return [valuesDictionary autorelease]; } - (NSArray*)dataStructuresFromManagedObjects:(NSArray*)managedObjects { NSMutableArray *dataArray = [[NSMutableArray alloc] init]; for (NSManagedObject *managedObject in managedObjects) { [dataArray addObject:[self dataStructureForManagedObject:managedObject]]; } return [dataArray autorelease]; } - (NSString*)jsonStructureFromManagedObjects:(NSArray*)managedObjects { NSArray *objectsArray = [self dataStructuresFromManagedObjects:managedObjects]; NSString *jsonString = [[CJSONSerializer serializer] serializeArray:objectsArray]; return jsonString; } - (NSManagedObject*)managedObjectFromStructure:(NSDictionary*)structureDictionary withManagedObjectContext:(NSManagedObjectContext*)moc { NSString *objectName = [structureDictionary objectForKey:@"ManagedObjectName"]; NSManagedObject *managedObject = [NSEntityDescription insertNewObjectForEntityForName:objectName inManagedObjectContext:moc]; [managedObject setValuesForKeysWithDictionary:structureDictionary]; for (NSString *relationshipName in [[[managedObject entity] relationshipsByName] allKeys]) { NSRelationshipDescription *description = [relationshipsByName objectForKey:relationshipName]; if (![description isToMany]) { NSDictionary *childStructureDictionary = [structureDictionary objectForKey:relationshipName]; NSManagedObject *childObject = [self managedObjectFromStructure:childStructureDictionary withManagedObjectContext:moc]; [managedObject setObject:childObject forKey:relationshipName]; continue; } NSMutableSet *relationshipSet = [managedObject mutableSetForKey:relationshipName]; NSArray *relationshipArray = [structureDictionary objectForKey:relationshipName]; for (NSDictionary *childStructureDictionary in relationshipArray) { NSManagedObject *childObject = [self managedObjectFromStructure:childStructureDictionary withManagedObjectContext:moc]; [relationshipSet addObject:childObject]; } } return managedObject; } - (NSArray*)managedObjectsFromJSONStructure:(NSString*)json withManagedObjectContext:(NSManagedObjectContext*)moc { NSError *error = nil; NSArray *structureArray = [[CJSONDeserializer deserializer] deserializeAsArray:json error:&error]; NSAssert2(error == nil, @"Failed to deserialize\n%@\n%@", [error localizedDescription], json); NSMutableArray *objectArray = [[NSMutableArray alloc] init]; for (NSDictionary *structureDictionary in structureArray) { [objectArray addObject:[self managedObjectFromStructure:structureDictionary withManagedObjectContext:moc]]; } return [objectArray autorelease]; } 

Agora, isso é recursivo, para que você possa facilmente traduzir todo o seu armazenamento persistente se não for cuidadoso. Observe seus relacionamentos e certifique-se de que eles apenas “baixem” a tree de objects para que você obtenha apenas os objects que deseja traduzir.

Eu só queria apontar um pequeno erro de digitação, que causou a falha do código, e espero que isso economize alguns minutos.

 - (NSArray*)dataStructuresFromManagedObjects:(NSArray*)managedObjects { NSMutableArray *dataArray = [[NSArray alloc] init]; for (NSManagedObject *managedObject in managedObjects) { [dataArray addObject:[self dataStructureFromManagedObject:managedObject]]; } return [dataArray autorelease]; } 

O NSMutableArray *dataArray = [[NSArray alloc] init]; // This should be NSMutableArray NSMutableArray *dataArray = [[NSArray alloc] init]; // This should be NSMutableArray

realmente deve ser NSMutableArray *dataArray = [[NSMutableArray alloc] init];

isso é tudo.

obrigado

A Sincronização de Dados Principais com Rails é uma apresentação detalhada que inclui código de amostra para serializar / desserializar seus objects Core Data de / para JSON (pule para o slide 55 para a parte Core Data). Seu código de amostra pressupõe um modelo bastante simples sem relacionamentos, embora eu ache que seria muito fácil estendê-lo.

A apresentação também apresenta alguns detalhes sobre como manter seu modelo de Core Data em sincronia com um aplicativo da Web baseado em REST, com pointers para algumas bibliotecas úteis, incluindo ObjectiveResource e ASIHTTPRequest . Não tenho certeza se é isso que você está tentando fazer, mas vale a pena dar uma olhada até mesmo no código de dados principais.

Se você tiver um NSDate no seu object gerenciado, como mencionado acima em um dos comentários, você terá problemas para serializar o object que contém o NSDate . Uma correção simples é adicionar um método NSDate ao NSDate usando categorias NSDate -c.

Adicione estes dois arquivos ao seu projeto:

NSdate.h:

 #import  @interface NSDate (jsondatarepresentation) - (NSData*) JSONDataRepresentation; @end 

NSDate.m:

 #import "NSDate.h" @implementation NSDate (jsondatarepresentation) - (NSData*) JSONDataRepresentation { return [[[NSNumber numberWithDouble:[self timeIntervalSince1970]] stringValue] dataUsingEncoding:NSUTF8StringEncoding]; } @end 

Há uma lib que faz a synchronization JSON para você: https://github.com/sixdegrees/lidenbrock

Me deparei com este post que funciona muito bem.

http://touchalicious.com/blog/2009/10/25/turn-core-data-models-into-json.html

Como isso é recursivo, os relacionamentos muitos-para-muitos continuarão se repetindo. Para evitar isso, adicionei uma chave “isExportable” ao dictionary de informações do usuário dos relacionamentos em meu modelo de dados principais. Você pode verificar essa chave e optar por não percorrer as relações sem ela.

insira a descrição da imagem aqui

 if ([property isKindOfClass:[NSRelationshipDescription class]]) { NSRelationshipDescription *relationshipDescription = (NSRelationshipDescription *)property; if ([[[relationshipDescription userInfo] objectForKey:@"isExportable"] boolValue] == YES) { NSString *name = [relationshipDescription name]; if ([relationshipDescription isToMany]) { NSMutableArray *arr = [properties valueForKey:name]; if (!arr) { arr = [[NSMutableArray alloc] init]; [properties setValue:arr forKey:name]; } for (NSManagedObject *o in [self mutableSetValueForKey:name]) { [arr addObject:[o propertiesDictionary]]; } } else { NSManagedObject *o = [self valueForKey:name]; [properties setValue:[o propertiesDictionary] forKey:name]; } } } } 

Apenas pensei em postar uma atualização rápida para essa questão. Eu segui as respostas por Marcus e Brandon e veio com isso para exportação JSON (ele ainda usa o TouchJSON):

 - (NSData*)jsonStructureFromManagedObjects:(NSArray*)managedObjects { NSArray *objectsArray = [self dataStructuresFromManagedObjects:managedObjects]; NSData *jsonData = [[CJSONSerializer serializer] serializeArray:objectsArray error:nil]; return jsonData; } - (NSArray*)dataStructuresFromManagedObjects:(NSArray*)managedObjects { NSMutableArray *dataArray = [[NSMutableArray alloc] init]; for (NSManagedObject *managedObject in managedObjects) { [dataArray addObject:[self dataStructureFromManagedObject:managedObject]]; } return dataArray; } - (NSDictionary*)dataStructureFromManagedObject:(NSManagedObject*)managedObject { NSDictionary *attributesByName = [[managedObject entity] attributesByName]; NSDictionary *relationshipsByName = [[managedObject entity] relationshipsByName]; NSMutableDictionary *valuesDictionary = [[managedObject dictionaryWithValuesForKeys:[attributesByName allKeys]] mutableCopy]; [valuesDictionary setObject:[[managedObject entity] name] forKey:@"ManagedObjectName"]; for (NSString *relationshipName in [relationshipsByName allKeys]) { NSRelationshipDescription *description = [[[managedObject entity] relationshipsByName] objectForKey:relationshipName]; if ([[[description userInfo] objectForKey:@"isExportable"] boolValue] == YES) { if (![description isToMany]) { NSManagedObject *relationshipObject = [managedObject valueForKey:relationshipName]; if (relationshipObject) { [valuesDictionary setObject:[self dataStructureFromManagedObject:relationshipObject] forKey:relationshipName]; } continue; } NSSet *relationshipObjects = [managedObject valueForKey:relationshipName]; NSMutableArray *relationshipArray = [[NSMutableArray alloc] init]; for (NSManagedObject *relationshipObject in relationshipObjects) { [relationshipArray addObject:[self dataStructureFromManagedObject:relationshipObject]]; } [valuesDictionary setObject:relationshipArray forKey:relationshipName]; } } return valuesDictionary; } 

Eu não consegui fazer a importação funcionar, talvez isso tenha algo a ver com o fato de que estou usando o Magical Record, não tenho certeza, então estou apenas fazendo um loop através do stream JSON de input e criando objects manualmente …

Marcus S. Zarra me inspirou a trazer a ideia recursiva para uma versão funcional. Nesta versão você não precisa definir uma chave no CoreData e pode recortar e colar no seu projeto 🙂

 // MARK: - encoding and decoding CoreData entity to dictionary func dataStructureFromManagedObject( managedObject:NSManagedObject?, parentEntity: NSEntityDescription? = nil) -> NSMutableDictionary { if (managedObject != nil) { var attributesByName: NSDictionary = managedObject!.entity.attributesByName var relationshipsByName: NSDictionary = managedObject!.entity.relationshipsByName var valuesImmutableDictionary: NSDictionary = managedObject!.dictionaryWithValuesForKeys( attributesByName.allKeys) var valuesDictionary: NSMutableDictionary = valuesImmutableDictionary.mutableCopy() as NSMutableDictionary valuesDictionary.setObject( managedObject!.entity.name!, forKey: "ManagedObjectName") for relationshipNameObject in relationshipsByName.allKeys { var relationshipName: NSString = relationshipNameObject as NSString var relationshipDescription: NSRelationshipDescription? = relationshipsByName.objectForKey( relationshipName) as? NSRelationshipDescription if !relationshipDescription!.toMany { // ono to one if parentEntity == nil || (relationshipDescription! as NSRelationshipDescription).destinationEntity != parentEntity! { // no parent or relationship is "downward" -> object for relationship must be added var relationshipObject: NSManagedObject? = managedObject!.valueForKey( relationshipName) as? NSManagedObject var relationshipObjectDictionary: NSMutableDictionary = self.dataStructureFromManagedObject( relationshipObject, parentEntity: managedObject?.entity) valuesDictionary.setObject( relationshipObjectDictionary, forKey: relationshipName) } else { // relationship is "upward" -> nothing to do } } else { // one to many -> all objects must be added var relationshipObjects: NSSet = managedObject!.mutableSetValueForKey( relationshipName) var relationshipArray:NSMutableArray = [] for relationshipObjectRaw in relationshipObjects { var relationshipObject:NSManagedObject? = relationshipObjectRaw as? NSManagedObject if relationshipObject != nil && !relationshipObject!.entity.isKindOfEntity( managedObject!.entity) { relationshipArray.addObject(self.dataStructureFromManagedObject( relationshipObject, parentEntity: managedObject?.entity)) } } valuesDictionary.setObject( relationshipArray, forKey: relationshipName) } } return valuesDictionary } else { return NSMutableDictionary() } } func managedObjectFromStructure( structureDictionary: NSDictionary, moc: NSManagedObjectContext, parentObject: NSManagedObject? = nil) -> NSManagedObject { if structureDictionary.count > 0 { var objectName:NSString = structureDictionary.objectForKey( "ManagedObjectName") as NSString var managedObject:NSManagedObject = NSEntityDescription.insertNewObjectForEntityForName( objectName, inManagedObjectContext: moc) as NSManagedObject var relationshipsByName: NSDictionary = managedObject.entity.relationshipsByName var realObjectStructure:NSMutableDictionary = structureDictionary.mutableCopy() as NSMutableDictionary realObjectStructure.removeObjectForKey( "ManagedObjectName") for key in realObjectStructure.allKeys { // search for "ManagedObjectName" relationship entrys and delete them before filling the managedObject from this structure for relationshipName in relationshipsByName.allKeys { if relationshipName as NSString == key as NSString { realObjectStructure.removeObjectForKey( key) } } } managedObject.setValuesForKeysWithDictionary( realObjectStructure) // the main object with attributes is created. Now care about the relationships for relationshipName in managedObject.entity.relationshipsByName.keys { var description:NSRelationshipDescription = relationshipsByName.objectForKey( relationshipName) as NSRelationshipDescription if !description.toMany { // to one relationship if parentObject == nil || description.destinationEntity != parentObject!.entity { // no parent or relationship is "downward" -> recurse structure to add var childStructureDictionary:NSDictionary = structureDictionary.objectForKey( relationshipName) as NSDictionary if childStructureDictionary.count > 0 { // dictionary not empty -> object must be created and added var childObject:NSManagedObject? = self.managedObjectFromStructure( childStructureDictionary, moc: moc, parentObject: managedObject) // validateForUpdate var error:NSError? if !managedObject.validateForUpdate( &error) { println("Error: Object not in valid state for update!!! -> \(error)") } else { managedObject.setValue( childObject, forKey: relationshipName as NSString) } } else { // relationship is "upward" -> nothing to do } } } else { // to many relationship var relationshipSet:NSMutableSet = managedObject.mutableSetValueForKey( relationshipName as NSString) var relationshipArray:NSArray = structureDictionary.objectForKey( relationshipName as NSString) as NSArray for childStructureDictionary in relationshipArray { if childStructureDictionary.count > 0 { // dictionary not empty -> object must be created and added var childObject:NSManagedObject = self.managedObjectFromStructure( childStructureDictionary as NSDictionary, moc: moc, parentObject: managedObject) // validateForUpdate var error:NSError? if !managedObject.validateForUpdate( &error) { println( "Error: Object not in valid state for update!!! -> \(error)") } else { relationshipSet.addObject( childObject) } } else { // no object was behind the relationship -> nothing to do } } // save set managedObject.setValue( relationshipSet, forKey: relationshipName as NSString) } } // final check validateForUpdate var error:NSError? if !managedObject.validateForUpdate( &error) { println( "Error: Object not in valid state for update although all previous check are passed!!! -> \(error)") } return managedObject } else { println( "Error: structure for object was empty. this should not happen at this point") var objectName:NSString = structureDictionary.objectForKey( "ManagedObjectName") as NSString var managedObject:NSManagedObject = NSEntityDescription.insertNewObjectForEntityForName( objectName, inManagedObjectContext: moc) as NSManagedObject return managedObject } } func dataStructuresFromManagedObjects( managedObjects: NSArray) -> NSArray { var dataArray:NSMutableArray = [] for managedObject in managedObjects { dataArray.addObject( self.dataStructureFromManagedObject(managedObject as? NSManagedObject)) } return dataArray } 

A chave aqui é passar a entidade pai como argumento para a recursion, para que possamos decidir qual relacionamento devemos preencher com os dados. Portanto, as duas funções: dataStructureFromManagedObject e managedObjectFromStructure podem codificar e decodificar qualquer object de entidade de CoreData em um dictionary e de volta a um object.