2013-07-01 43 views
1

我有一些從URL中提取的JSON數據。我編寫的代碼可以很好地下載JSON並解析它,但我似乎無法訪問它,尤其是在數據作爲另一個子元素包含的情況下。從NSJSONSerialization的數據中獲取值

這裏是JSON格式:

{ 
    address = "<null>"; 
    city = "<null>"; 
    country = UK; 
    "country_code" = GB; 
    daylight = 1; 
    for = daily; 
    items =  (
       { 
      asr = "5:22 pm"; 
      "date_for" = "2013-7-1"; 
      dhuhr = "1:01 pm"; 
      fajr = "2:15 am"; 
      isha = "11:47 pm"; 
      maghrib = "9:24 pm"; 
      shurooq = "4:39 am"; 
     } 
    ); 
    latitude = "50.9994081"; 
    link = "http://muslimsalat.com/UK"; 
    longitude = "0.5039011"; 
    "map_image" = "http://maps.google.com/maps/api/staticmap?center=50.9994081,0.5039011&sensor=false&zoom=13&size=300x300"; 
    "postal_code" = "<null>"; 
    "prayer_method_name" = "Muslim World League"; 
    "qibla_direction" = "119.26"; 
    query = "51.000000,0.500000"; 
    state = "<null>"; 
    timezone = 0; 
    title = UK; 
    "today_weather" =  { 
     pressure = 1020; 
     temperature = 14; 
    }; 
} 

(這些是伊斯蘭祈禱時間。)

我的Objective-C的到目前爲止是這樣的:

-(CLLocationCoordinate2D) getLocation{ 
    CLLocationManager *locationManager = [[[CLLocationManager alloc] init] autorelease]; 
    locationManager.delegate = self; 
    locationManager.desiredAccuracy = kCLLocationAccuracyBest; 
    locationManager.distanceFilter = kCLDistanceFilterNone; 
    [locationManager startUpdatingLocation]; 
    CLLocation *location = [locationManager location]; 
    CLLocationCoordinate2D coordinate = [location coordinate]; 

    return coordinate; 
} 

//class to convert JSON to NSData 
- (IBAction)getDataFromJson:(id)sender { 
    //get the coords: 
    CLLocationCoordinate2D coordinate = [self getLocation]; 
    NSString *latitude = [NSString stringWithFormat:@"%f", coordinate.latitude]; 
    NSString *longitude = [NSString stringWithFormat:@"%f", coordinate.longitude]; 

    NSLog(@"*dLatitude : %@", latitude); 
    NSLog(@"*dLongitude : %@",longitude); 

    //load in the times from the json 
    NSString *myURLString = [NSString stringWithFormat:@"http://muslimsalat.com/%@,%@/daily/5.json", latitude, longitude]; 
    NSURL *url = [NSURL URLWithString:myURLString]; 
    NSData *jsonData = [NSData dataWithContentsOfURL:url]; 

    if(jsonData != nil) 
    { 
     NSError *error = nil; 
     id result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error]; 
     NSArray *jsonArray = (NSArray *)result; //convert to an array 
     if (error == nil) 
      NSLog(@"%@", result); 
      NSLog(@"%@", jsonArray); 
      for (id element in jsonArray) { 
       NSLog(@"Element: %@", [element description]); 

      } 
    } 
} 

運行此代碼,我得到的唯一輸出是元素名稱列表(address, city, country,依此類推)。給出了items,但不是其子元素。據我所知,這是我要求的代碼用於:

for (id element in jsonArray) { 
    NSLog(@"Element: %@", [element description]); 
} 

,但我不知道如何移動到下一個步驟。

我需要的唯一數據值其實是時代本身(所以,items>asr,items>dhuhr等)。

我怎樣才能得到這些價值自己,然後將它們保存爲我可以使用的值?

謝謝!

回答

3

NSArray *jsonArray = (NSArray *)result; //convert to an array

這不 '轉換' ,這只是你承諾編譯器result真的是NSArray。在這種情況下,這是一個謊言。

您的代碼當前只是打印JSON中返回的字典中的鍵列表。試試這個去的項目清單(它是一個數組,所以你需要對付有可能是多個條目):

NSDictionary *result = [NSJSONSerialization ... 

for (NSDictionary *itemDict in result[@"items"]) { 
    NSLog(@"item: %@", itemDict); 
} 

然後你就可以提取倍。

+0

謝謝,效果很好。 – samiles

4

(...); - is Array

{...}; - 是字典

讓你的 「元素」 是字典

使用objectForKey:

例如:

for (id element in jsonArray) { 
    NSLog(@"Element asr: %@", [element objectForKey:@"asr"]); // or element[@"asr"] 
} 
+0

嗯,這看起來對我好,但是當我運行該應用程序退出。它轉到'線程1:信號SIGBART'並輸出堆棧跟蹤。任何想法爲什麼? – samiles

1

您可以通過以下提取信息:

NSError* error = nil; 
NSDictionary *userInfo; //your main data 

if([NSJSONSerialization class]) 
    userInfo = [NSJSONSerialization JSONObjectWithData:[request responseData] options:kNilOptions error:&error]; 

//to extract items 
    NSDictionary *items = [[[userInfo objectForKey:@"items"] JSONValue] objectAtIndex:0];