2015-07-18 78 views
-2

我有一些JSON存儲爲NSString,我試圖將其轉換爲NSDictionary並在我的JSON中獲取'EndDate'的值。從xcode獲取存儲爲NSString的JSON的值

我想從JSON檢索'EndDate',但由於水平的數量,我不太確定我應該如何實現它。

這裏是JSON:

{ "GetResponse":{ "GetResult":{ "Faults":null, "Response":{ "Asset":{ "AssetParts":{ "@nil":"true" }, "CountryLookupCode":808, "Number」:24234, "Duplicate":"false", "Code":"`123」, "Channel」:」SR」, 「Desc」:」Test」, "Number」:123, 「Mandate」:{ "@nil":"true" }, 「TestTime」:」True」, 「Date」:」2010-08-12T19:00:00", 「Results」:{ 「Details」:[ { "EndDate":"2013-08-13T18:59:59", 「Type」:」Taken」, "Item」:」902」, 「Level」:」SL」, 「Description」:」Timed」, 「Group」:1, 「Prov」:{ "@nil":"true" }, "StartDate":"2010-08-12T19:00:00" }, { "EndDate":"2013-08-13T18:59:59", 「Machine」:」Dated」, 「Country」:」UK」, "Code":"CCDD」, 「Description」:」Addressed」, 「Level」:2, "Provider":{ "@nil":"true" }, "StartDate":"2010-08-12T19:00:00" }, { "EndDate":"2013-08-13T18:59:59", "Type」:」Title」, "ItemNumber」:」1253」, "Service":"NEDD」, 「Desc」:」Down」, 「Grp」:5, "Provider":{ "@nil":"true" }, "StartDate":"2010-08-12T19:00:00" } ] } } } } } } 

這裏是我的代碼:

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
     [request setURL:[NSURL URLWithString:@"https://192.168.0.20/test.json"]]; 
     [request setHTTPMethod:@"GET"]; 

     NSURLResponse *requestResponse; 
     NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:nil]; 

     NSString *requestReply = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding]; 
     //NSLog(@"requestReply: %@", requestReply); 
     //End 
     NSData *data = [requestReply dataUsingEncoding:NSUTF8StringEncoding]; 
     id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; 

     NSArray *performersArray = [json objectForKey:@"GetResponse"]; 
     for (NSDictionary *performerDic in performersArray) { 
      NSLog(@"%@", [performerDic objectForKey:@"EndDate"]); 
     } 

感謝

+0

嗨。檢查你的json文件。 'NSArray * performersArray = [json objectForKey:@「GetResponse」];'是錯誤的。 '[json objectForKey:@「GetResponse」]' - 返回一個NSDictionary。 –

+0

我認爲,如果我錯了,抱歉,您輸入的JSON缺少某些內容。這裏是一個URL,你可以檢查你的數據,看看你的JSON是如何http://jsonviewer.stack.hu。網站無法轉換您的JSON,我說的原因是。 –

+0

'requestReply'不需要,'data'也不需要'requestHandler'。 'NSASCIIStringEncoding'幾乎總是一個壞主意,'NSUTF8StringEncoding'幾乎總是更好。如果你想從數據使用中得到一個字符串:'initWithData:encoding'。 – zaph

回答

1
NSArray *detailsArray = json[@"GetResponse"][@"GetResult"][@"Response"][@"Asset"][@"Results"][@"Details"]; 
for (NSDictionary *detailsDict in detailsArray){ 
    NSLog(@"%@",detailsDict[@"EndDate"]); 
} 

這應該工作