NSManagedObject to JSON

2019-07-07 11:21发布

问题:

I have an entity class called catObras, and it inherits from the class NSManagedObject. What I want to do is pass it trough a web service (POST) in JSON form. If I sent the object I receive this:

<catObras: 0x6d879f0> (entity: catObras; id: 0x6d859b0 <x-coredata://41B60B06-248C-488D-A14C-894E04D0395F/catObras/p2> ; data: {
Reporte = "<relationship fault: 0x6d9dc40 'Reporte'>";
calendarioVisitas = "<relationship fault: 0x6dac2c0 'calendarioVisitas'>";
catFondosInversion = "<relationship fault: 0x6d7a1b0 'catFondosInversion'>";
contratista = nil;
contrato = "XX-AYTO-ENS-BC-HABITAT-2011-IS-01";
descripcion = "AMPLIACION DE RED DE DRENAJE SANITARIO COL. VISTA HERMOSA";
direccion = nil;
estatus = nil;
fechaAprobacion = "2012-01-01 08:00:00 +0000";
fechaInicio = "2012-01-31 08:00:00 +0000";
fechaTerminacion = "2012-03-10 08:00:00 +0000";
fechaUltimoRep = nil;
idAgrupacion = 0;
idObra = 5;
inversionAprobada = 0;
inversionAutorizada = 1668000;
inversionContratada = 834000;
nota = asdasdasdasda;
numeroControl = "";
obraPartidas = "<relationship fault: 0x6d7a1f0 'obraPartidas'>";
observaciones = "muestras 2";
oficioAprobacion = "SDS/122/11/1857 OF.001";
supervisor = nil;})

I would like to pass this information in json form. Right now I'm using SBJSON (aka JSON-framework). When I try to use JSONRepresentation, it sends me this:

JSONRepresentation failed. Error is: Not valid type for JSON

Any suggestions?

回答1:

I'm not familiar with SBJSON, but my guess is that -JSONRepresentation is meant to be called on NSDictionaries, not arbitrary objects. You could do this:

NSManagedObject *managedObject = ...;
NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", ..., nil]; // These are the keys for the properties of your managed object that you want in the JSON
NSString *json = [[managedObject dictionaryWithValuesForKeys:keys] JSONRepresentation];

The -dictionaryWithValuesForKeys: method is described in the documentation. Importantly it returns an NSDictionary, which SBJSON can probably handle. You'll need to be careful with the types of each attribute on your NSManagedObject subclass, being sure that they are of a type that SBJSON can handle.