2010-03-10 17 views
6

Tengo el siguiente JSON objeto:analizar los objetos JSON anidadas con Marco JSON para Objective-C

{ 
"response": { 
    "status": 200 
}, 
"messages": [ 
    { 
     "message": { 
      "user": "value" 
      "pass": "value", 
      "url": "value" 
     } 
] 
    } 

}

estoy usando JSON-marco (también tratado JSON táctil) para analizar a través de esto y crea un diccionario Quiero acceder al bloque "mensaje" y extraer los valores "usuario", "pasar" y "url".

En Obj-C Tengo el siguiente código:

// Create new SBJSON parser object 
SBJSON *parser = [[SBJSON alloc] init]; 

// Prepare URL request to download statuses from Twitter 
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:myURL]]; 

// Perform request and get JSON back as a NSData object 
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; 

// Get JSON as a NSString from NSData response 
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]; 

//Print contents of json-string 
NSArray *statuses = [parser objectWithString:json_string error:nil]; 
NSLog(@"Array Contents: %@", [statuses valueForKey:@"messages"]); 
NSLog(@"Array Count: %d", [statuses count]); 


NSDictionary *results = [json_string JSONValue]; 
NSArray *tweets = [[results objectForKey:@"messages"] objectForKey:@"message"]; 

for (NSDictionary *tweet in tweets) 
{ 
    NSString *url = [tweet objectForKey:@"url"]; 
    NSLog(@"url is: %@",url); 
} 

puedo saco "mensajes" y ver todos los "mensajes" bloques, pero no soy capaz de analizar más profundamente y extraer el " usuario "," pase "y" url ".

+0

El JSON la cuerda está mal formada, de la forma que la has escrito aquí. El conjunto de mensajes tiene dos llaves abiertas, y solo un cierre. – Felixyz

Respuesta

9

resuelto:

NSArray *tweets = [[results objectForKey:@"messages"] valueForKey:@"message"]; 
+0

¿Puede explicar esta respuesta un poco más? – Dewseph

6
Array({ 

    0=>Dictionary({ 

     response = Array({ 

     0=>Dictionary(Status = 200) 

     }) 

    }), 

    1=>Dictionary({ 

     messages = Array({ 

     0=> Dictionary({ 

      message = Array({ 

      0=>Dictionary({ 

       user = value, 

       pass=value, 

       url=value 

      }) 

      }) 

     }) 

     }) 

    }) 

}) 

lo tanto, para acceder Inglés para el usuario, pase, url,

nsarray *arr = jsonmainarray; 


arr = [[[jsonmainarray objectAtIndex: 1] objectforkey:@"messages"] objectatindex: 0]; 



nsdictionary *dict = [arr objectatindex: 0]; 

arr = [dict objectforkey:@"message"]; 

dict = [arr objectatindex: 0]; // Dictionary with user, pass, url 
+0

Gr8 ................ –

2

hay una manera más fácil (en mi opinión) para hacer análisis JSON:)

- (void)loadJSONData:(NSString *)u{ 
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://expandurl.appspot.com/expand?url=%@", u]]; 
    NSData *rawJsonData = [NSData dataWithContentsOfURL:url]; 

    CJSONDeserializer *parser = [CJSONDeserializer new]; 
    NSError *error; 
    NSDictionary *jsonDictionary = [parser deserializeAsDictionary:rawJsonData error:&error]; 

    [parser release]; 

    NSArray *array = [jsonDictionary objectForKey:@"urls"]; 
} 

Todo lo que tienes que hacer es usar JSON touch ... como menciona Sheehan Alam.

decir que usted tiene esta línea de datos JSON:

{ "end_url" = "http://www.youtube.com"; redirects = 0; "start_url" = "http://www.youtube.com"; estado = OK; urls = ( "http://www.youtube.com" ); }

entonces en sus JSONDictonary los datos se puede acceder haciendo:

[jsonDictionary objectForKey:@"urls"]; //This will return an Array since URLS is a array 
[jsondictionary objectForKey:@"en_url"]; //this will return an NSString since end_url is a string 

Espero que esta ayuda a la gente tanto como me ha ayudado =)

atentamente Kristian

Cuestiones relacionadas