2012-05-11 27 views
23

tengo una clase C como objetivo,Convertir un objetivo c objeto iOS a una cadena JSON

@interface message : NSObject { 
NSString *from; 
NSString *date; 
NSString *msg; 
} 

Tengo una NSMutableArray de las instancias de esta clase de mensaje. Deseo serializar todas las instancias en NSMutableArray en un archivo JSON, utilizando las nuevas API JSONSerialization en iOS 5 SDK. Cómo puedo hacer esto ?

Está creando un NSDictionary de cada clave, iterando a través de cada instancia de los elementos en el NSArray? ¿Alguien puede ayudar con el código de cómo resolver esto? No puedo obtener buenos resultados en Google, ya que "JSON" sesga los resultados a las llamadas del lado del servidor y la transferencia de datos en lugar de la serialización. Muchas gracias.

EDIT:

NSError *writeError = nil; 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:notifications options:NSJSONWritingPrettyPrinted error:&writeError]; 
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; 
NSLog(@"JSON Output: %@", jsonString); 

Respuesta

35

EDIT: He hecho una aplicación ficticia que debe ser un buen ejemplo para usted.

Creo una clase de Mensaje desde su fragmento de código;

//Message.h 
@interface Message : NSObject { 
    NSString *from_; 
    NSString *date_; 
    NSString *msg_; 
} 

@property (nonatomic, retain) NSString *from; 
@property (nonatomic, retain) NSString *date; 
@property (nonatomic, retain) NSString *msg; 

-(NSDictionary *)dictionary; 

@end 

//Message.m 
#import "Message.h" 

@implementation Message 

@synthesize from = from_; 
@synthesize date = date_; 
@synthesize msg = mesg_; 

-(void) dealloc { 
    self.from = nil; 
    self.date = nil; 
    self.msg = nil; 
    [super dealloc]; 
} 

-(NSDictionary *)dictionary { 
    return [NSDictionary dictionaryWithObjectsAndKeys:self.from,@"from",self.date, @"date",self.msg, @"msg", nil]; 
} 

Luego configuré un NSArray de dos mensajes en el AppDelegate. El truco es que no solo el objeto de nivel superior (notificaciones en su caso) necesita ser serializable, sino también todos los elementos que las notificaciones contienen: Por eso creé el método del diccionario en la clase Message.

//AppDelegate.m 
... 
Message* message1 = [[Message alloc] init]; 
Message* message2 = [[Message alloc] init]; 

message1.from = @"a"; 
message1.date = @"b"; 
message1.msg = @"c"; 

message2.from = @"d"; 
message2.date = @"e"; 
message2.msg = @"f"; 

NSArray* notifications = [NSArray arrayWithObjects:message1.dictionary, message2.dictionary, nil]; 
[message1 release]; 
[message2 release]; 


NSError *writeError = nil; 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:notifications options:NSJSONWritingPrettyPrinted error:&writeError]; 
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; 
NSLog(@"JSON Output: %@", jsonString); 

@end 

La salida cuando corro la aplicación es por lo tanto:

2012-05-11 11: 58: 36.018 pila [3146: F803] Salida JSON: [ { "MSG": " c " "de": "a", "fecha": "b" }, { "msg": "f", "de": "d", "fecha":" e " } ]

RESPUESTA ORIGINAL:

¿Es this la documentación que busca?

+0

El PO primero tendrá que convertir su objeto a un diccionario, pero eso es bastante sencillo (un método estático hará el truco) – user439407

+1

Damo: que la página no explica acerca de cómo convertir una matriz de clase personalizada a JSON . Eso es lo que estoy luchando por encontrar. –

+0

Si todos los ivars de su clase son NSString, debería funcionar mágicamente ... advertencia: No he intentado esto. – Damo

8

Ahora puede resolver este problema fácilmente usando JSONModel. JSONModel es una biblioteca que serializa/deserializa genéricamente su objeto en función de la clase. Incluso puede usar non-nsobject basado en propiedades como int, short y float. También puede atender el JSON anidado complejo. Maneja la comprobación de errores por usted.

Deserializar el ejemplo. en el archivo de cabecera:

#import "JSONModel.h" 

@interface Message : JSONModel 
@property (nonatomic, strong) NSString* from; 
@property (nonatomic, strong) NSString* date; 
@property (nonatomic, strong) NSString* message; 
@end 

en el archivo de aplicación:

#import "JSONModelLib.h" 
#import "yourPersonClass.h" 

NSString *responseJSON = /*from somewhere*/; 
Message *message = [[Message alloc] initWithString:responseJSON error:&err]; 
if (!err) 
{ 
    NSLog(@"%@ %@ %@", message.from, message.date, message.message): 
} 

Serialize Ejemplo.En archivo de implementación:

#import "JSONModelLib.h" 
#import "yourPersonClass.h" 

Message *message = [[Message alloc] init]; 
message.from = @"JSON beast"; 
message.date = @"2012"; 
message.message = @"This is the best method available so far"; 

NSLog(@"%@", [person toJSONString]); 
+1

¡Gracias! Esta libiary es muy útil. – BlackMamba

2

Nota: Esto solo funcionará con objetos serializables. Esta respuesta fue proporcionada anteriormente en una edición en la propia pregunta, pero yo siempre busque respuestas en la sección "respuestas" a mí mismo ;-)

- (NSString*) convertObjectToJson:(NSObject*) object 
{ 
    NSError *writeError = nil; 

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:&writeError]; 
    NSString *result = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; 

    return result; 
} 
+0

Hola. Cómo convertir una matriz de NSObject. Gracias :) – kemdo

+0

hey @kemdo - no estoy seguro - y no estoy haciendo ios dev más, así que realmente no puedo decir ... ¡Buena suerte! –

0

Aquí es una biblioteca que utilicé en mis proyectos BWJSONMatcher, que puede ayudar puede unir fácilmente su json string con su modelo de datos con no más de una línea de código.

... 
NSString *jsonString = @"{your-json-string}"; 
YourValueObject *dataModel = [YourValueObject fromJSONString:jsonString]; 

NSDictionary *jsonObject = @{your-json-object}; 
YourValueObject *dataModel = [YourValueObject fromJSONObject:jsonObject]; 
... 
YourValueObject *dataModel = instance-of-your-value-object; 
NSString *jsonString = [dataModel toJSONString]; 
NSDictionary *jsonObject = [dataModel toJSONObject]; 
... 
Cuestiones relacionadas