2012-07-11 56 views
0

我試圖建立我的NSDictionnary發送到使用AFNetworking框架的請求,但似乎我很困惑如何正確地做到這一點。AFNetworking - 建立NSDictionary參數

這裏是服務器的期待:

{ 
    "limit":10, 
    "filters": 
    [ 
     {"field":"owner","operator":"EQUAL","value":"ownerId","type":"integer"}, 
     {"field":"date","operator":"GE","value":"30 Jun 2010 00:00:00","type":"date"}, 
    ], 
    "order":[{"field":"date","order":"ASC"}], 
    "page":0 
} 

我試圖做(我真的不知道,如果它這樣做TBH正確的方式),是建立一個的NSDictionary像以下:

NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys: 
           @"10", @"chunkSize", 
           [NSDictionary dictionaryWithObjectsAndKeys: 
            [NSDictionary dictionaryWithObjectsAndKeys:@"owner", @"field", @"EQUAL", @"operator", @"ownerId", @"value", @"integer", @"type", nil], 
            [NSDictionary dictionaryWithObjectsAndKeys:@"date", @"field", @"GE", @"operator", @"30 Jun 2010 00:00:00", @"value", @"date", @"type", nil], 
            nil], @"filters", 
           [NSDictionary dictionaryWithObjectsAndKeys: 
            [NSDictionary dictionaryWithObjectsAndKeys:@"date", @"field", @"ASC", @"order", nil], 
            nil], @"order", 
           @"0", @"page", 
           nil]; 

但我下面的錯誤當視圖加載:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', 
reason: '+[NSDictionary dictionaryWithObjectsAndKeys:]: second object of each pair must be non-nil 

我知道我擰ü p正確地構建參數,但是我無法在多次嘗試之後做到這一點。誰能幫忙?此外,我不知道我必須在這裏執行[]{}的區別。我讀{}是爲字典和[]爲數組,但我真的不知道如何翻譯它在我的情況。

回答

2

您的錯誤是,第3行開始的字典值需要包裝在數組中。

至少直到Objective-C array and hash literals成爲主流,我創建複雜字典的首選方法是從NSMutableDictionary構建它們。你的情況:

NSMutableDictionary *mutableParameters = [NSMutableDictionary dictionary]; 
[mutableParameters setValue:@"10" forKey:@"limit"]; 
// ... 

NSMutableArray *mutableFilters = [NSMutableArray array]; 
NSMutableDictionary *mutableOwnerFilterDictionary = [NSMutableDictionary dictionary]; 
[mutableOwnerFilterDictionary setValue:@"owner" forKey:@"field"]; 
// ... 
[mutableFilters addObject:mutableOwnerFilterDictionary]; 

[mutableParameters setValue:mutableFilters forKey:@"filters"]; 
// ... 

另外,一定要發送,超過作爲JSON通過設置AFJSONParameterEncodingAFHTTPClient

+0

感謝您的提示!那麼我會嘗試這種方式 – 2012-07-11 14:25:59

2

括號[]表示數組,而大括號{}表示對象(在此上下文中的字典)。要生成您需要的結構:

NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys: 
    @"10", @"chunkSize", 
    [NSArray arrayWithObjects: 
     [NSDictionary dictionaryWithObjectsAndKeys:@"owner", @"field", @"EQUAL", @"operator", @"ownerId", @"value", @"integer", @"type", nil], 
     [NSDictionary dictionaryWithObjectsAndKeys:@"date", @"field", @"GE", @"operator", @"30 Jun 2010 00:00:00", @"value", @"date", @"type", nil], 
     nil], @"filters", 
    [NSArray arrayWithObjects: 
     [NSDictionary dictionaryWithObjectsAndKeys:@"date", @"field", @"ASC", @"order", nil], 
     nil], @"order", 
    @"0", @"page", 
    nil];