0

私はjsonオブジェクトの解析で立ち往生しています。問題は、jsonオブジェクトをどのように解析するかです。これが私がログで応答を取得するものです。

{"0":{"**title**":"Test Event","url_title":"test_event1","status":"open","entry_date":"Sep 10, 2012, 

05:20:38AM","entry_id":"26","site_id":"1","channel_id":"3","field_dt_40":null,"field_dt_58":null,"channel_title":"News & 

Events","channel_name":"news_events","start_date":"1348120800","end_date":"1348120800","start_time": "43200","end_time":"46800","where":"FCF","news_event_description":"<p>\n\tLunch with group.<\/p>\n"},

"1":{"**title**":"Test Event 2","url_title":"test_event_2","status":"open","entry_date":"Sep 10, 2012, 05:20:08AM","entry_id":"28","site_id":"1","channel_id":"3","field_dt_40":null,"field_dt_58":null,"channel_title":"News & Events","channel_name":"news_events","start_date":"1348207200","end_date":"1348207200","start_time":"43200","end_time":"46800","where":"FCF - Lunch","news_event_description":"<p>\n\tThis was a great event.<\/p>\n"},

"2":{"**title**":"Test Event 3","url_title":"test_event_3","status":"open","entry_date":"Sep 10, 2012, 05:20:54AM","entry_id":"29","site_id":"1","channel_id":"3","field_dt_40":null,"field_dt_58":null,"channel_title":"News & Events","channel_name":"news_events","start_date":"1346738400","end_date":"1346738400","start_time":"7200","end_time":"11700","where":"FCF - Lunch","news_event_description":"<p>\n\tFall planning season.<\/p>\n"}}

問題は、テーブルビューにすべてのタイトルを表示したいということです。キー0、1、2を使用して単一のタイトルを取得できます。しかし、すべてのタイトルを一度に表示したいのですが、解析します

みんな助けてください、よろしくお願いします。

4

2 に答える 2

3

jsonDictがあなたのjson辞書だとしましょう...これを試してください

NSArray * keys=[[NSArray alloc]init];
keys=[jsonDict allKeys];
NSMutableArray *titles=[[NSMutableArray alloc]init];
for(int i=0;i<[keys count];i++){
      [titles addObject:[[jsonDict valueForKey:[keys objectAtIndex:i]]valueForKey:@"title"]];
}
NSLog(@"your array of titles : %@",titles); //use this array to fill your cell
于 2012-10-08T05:29:18.567 に答える
2

JSONを自分で解析しようとしていますか?TouchJSONやApple独自のNSJSONSerilizationなど、すでに十分にテストされているものを使用する方が簡単な場合があります。結果は、好きなように使用できるObjective-Cオブジェクトのグラフになります。

いずれにせよ、あなたが持っているのは辞書の辞書に相当するものです。と呼ばれるNSDictionaryとしてそれを持っている場合はmyJSONDictionary、次のように言うことができます。

NSArray *theObjects = [myJSONDictionary allValues]; // gets all the objects
NSArray *theTitles = [theObjects valueForKey:@"**title**"]; // gets all the titles

高速列挙を使用して辞書を反復処理することもできます。

NSMutableArray *theTitles = [NSMutableArray array];
for (NSString *key in myJSONDictionary) {
    NSDictionary *object = [myJSONDictionary objectForKey:key];
    NSString *title = [object objectForKey:@"**title**"];
    [theTitles addObject:title]
}

タイトルだけが必要な場合は、最初の例のようにKVCを使用する代わりにこれを行うことに実際の利点はありませんが、オブジェクトごとに行う作業がより複雑な場合は、これが正しい選択になる可能性があります。

于 2012-10-08T05:23:20.750 に答える