У меня есть следующий объект JSON:
{
"response": {
"status": 200
},
"messages": [
{
"message": {
"user": "value"
"pass": "value",
"url": "value"
}
]
}
}
Я использую JSON-платформу (также попробовал Касание JSON) проанализировать через это и создать словарь. Я хочу получить доступ к блоку "сообщения" и вывести "пользователя", "передачу" и значения "URL".
В Obj-C у меня есть следующий код:
// 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);
}
Я могу вытащить "сообщения" и видеть все блоки "сообщения", но я не могу проанализировать глубже и вывести "пользователя", "передачу" и "URL".
Решено:
NSArray *tweets = [[results objectForKey:@"messages"] valueForKey:@"message"];
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
})
})
})
})
})
})
Итак, чтобы получить доступ к словарю для пользователя, введите пароль, 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