Pregunta

Tengo algún problema con el análisis de JSON.Cuando llegué a URL, tengo la respuesta de JSON como esta:

//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 solo 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 obtener el valor de identificación, mensaje y remitente, y trabajar bien en JSON 1, pero error en JSON 2. Utilizo JSON-Framework.Y la pregunta es cómo detectar que la respuesta JSON es objeto ({}) o matriz ([]) ??

// 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"]);
}

¿Fue útil?

Solución

Puede usar id y verifique si el objeto que obtiene es NSARRAY o NSDicticionary como este:

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
}

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top