2010-07-18 13 views
5

Tengo algún problema con el análisis JSON. respuesta JSON cuando golpeo URL, Tengo la siguiente manera:Cómo detectar objeto JSON/matriz JSON en XCode utilizando JSON-Framework

//JSON 1 
{ "data": 
    {"array": 
    ["3", 
     {"array": 
      [ 
      {"id":"1","message":"Hello","sender":"inot"}, 
      {"id":"2","message":"World","sender":"inot"}, 
      {"id":"3","message":"Hi","sender":"marza"} 
      ] 
     } 
    ] 
    }, 
"message":"MSG0001:Success", 
"status":"OK" 
} 

Pero si el resultado de los datos es sólo 1, la respuesta JSON es así:

//JSON 2 
{ "data": 
    {"array": 
    ["3", 
     {"array": 
      {"id":"3","message":"Hi","sender":"marza"} 
     } 
    ] 
    }, 
"message":"MSG0001:Success", 
"status":"OK" 
} 

implemento este código para Obtenga el ID, el mensaje y el valor del remitente, y trabaje bien en JSON 1, pero el error en JSON 2. Utilizo JSON-Framework. Y la pregunta es cómo detectar que la respuesta JSON es object ({}) o array ([]) ??

// Parse the string into JSON 
NSDictionary *json = [myString JSONValue]; 

// Get all object 
NSArray *items = [json valueForKeyPath:@"data.array"]; 
NSArray *array1 = [[items objectAtIndex:1] objectForKey:@"array"]; 
NSEnumerator *enumerator = [array1 objectEnumerator]; 
NSDictionary* item; 
while (item = (NSDictionary*)[enumerator nextObject]) { 
    NSLog(@"id  = %@",[item objectForKey:@"id"]); 
    NSLog(@"message = %@",[item objectForKey:@"message"]); 
    NSLog(@"sender = %@",[item objectForKey:@"sender"]); 
} 

Respuesta

15

Puede utilizar id y comprobar si el objeto que se obtiene es NSArray o NSDictionary así:

id item = [json valueForKeyPath:@"data.array"]; 
if ([item isKindOfClass:[NSArray class]]) { 
    // item is an array 
} 
else if ([item isKindOfClass:[NSDictionary class]]) { 
    // item is a dictionary 
} 
+0

Gracias Michael Kessler, funciona ahora. – inot

+0

@inot, usted es más que bienvenido a marcar la respuesta como aceptada si resolvió su problema. –

Cuestiones relacionadas