2012-08-03 85 views
3

我是iOS新手。如何从NSData获取信息?

的NSData:

{ 
"results" : [ 
    { 
    "formatted_address" : "Proyezd Voskresenskiye Vorota, 3, Moscow, Russia, 109012", 
    "geometry" : { 
     "location" : { 
      "lat" : 55.75622380, 
      "lng" : 37.61855850 
     } 

我只需要 “的formatted_address”,你能不能帮我做一个的NSString中,这将是地址? 对不起,愚蠢的问题。

+2

你从哪里得到的数据?你有没有试过NSKeyedArchiver/Unarchiver? – 2012-08-03 15:09:30

+0

[[foo objectForKey:@“results”] objectAtIndex:0] objectForKey:@“formatted_address”];字典对象,获取对象关键的“结果”,它看起来像一个数组,从该数组中获取第一个对象(objectAtIndex:0)..这是一个字典.. get objectForKey formatted_address – 0x8badf00d 2012-08-03 15:18:36

回答

6

您的NSData是JSON响应,您需要创建一个NSDictionary才能访问数据的特定部分。一个NSDictionary只是将键映射到值。要获得值,请致电– objectForKey:。在你的情况下,你有一个字典作为关键“结果”的值。所以在你的情况下:

NSDictionary *results = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; 
NSDictionary *resultsDictionary = [[results objectForKey:@"results"] objectAtIndex:0]; 
NSString *formattedAddress = [resultsDictionary objectForKey:@"formatted_address"]; 
+0

非常感谢! – quaddef 2012-08-03 17:11:16

1

看看NSJSONSerialization类。还有就是你的数据转换成词典的方法:

+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error; 

有了这一点,你应该可以问你的新创建的NSDictionary检索您的NSString。