3

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?

Keplah
  • 954
  • 2
  • 13
  • 26
Alejandro Rangel
  • 1,670
  • 1
  • 20
  • 35

1 Answers1

7

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.

Andrew Madsen
  • 21,309
  • 5
  • 56
  • 97
  • yeah, i make an NSDictionary with the info an try to use de JSONRepresentation but i get this "-JSONRepresentation failed. Error is: JSON serialisation not supported for __NSDate" :( – Alejandro Rangel Feb 14 '12 at 19:49
  • 1
    There are a couple approaches, but perhaps the easiest is to create a new method on your NSManagedObject subclass called something like `-dateString`. In the method, use an NSDateFormatter to create a proper string representation of the date. Then put `dateString` in your keys array instead of `date`. – Andrew Madsen Feb 14 '12 at 19:53