2016-07-02 7 views
-1

私はサーバー通信を使ってiOSアプリケーションを開発中です。このような辞書を作るのに助けてくれる人がいますか?ここでネストされた辞書を作る方法、IOS - Objective C

{ 
    "api_key": "APIKey", 
    "items": [{ 
     "item_id": "10", 
        "quantity": "10" 
    }, { 
     "item_id": "11", 
        "quantity": "10" 
    }], 
    "user_id": "UserID", 
    "user_address": "address", 
    "user_number": "number" 

} 

は、あなたがキーと値の辞書のためのシンプルなメカニズムをペア設定することで、辞書を作成することができます

NSMutableArray *arrayItems = [NSMutableArray new]; 
for (int i=0; i<[ordeArray count]; i++) { 
    ItemBO *item = [ordeArray objectAtIndex:i]; 
    NSString *quantity = [NSString stringWithFormat:@"%i",item.quantity]; 
    NSDictionary *dic = @{@"quantity": quantity, @"item_id":item.itemID }; 
    [arrayItems addObject: dic]; 
} 
NSString * userID = [[NSUserDefaults standardUserDefaults] valueForKey:USERID]; 
NSDictionary *mainDictionary = [[NSDictionary alloc] initWithObjectsAndKeys: 

        APIKEY, @"api_key", 
          orderinfo.deliveryAddress , @"delivery_address", 
          orderinfo.deliveryTime , @"delivery_time", 
          orderinfo.contactNumber , @"delivery_contact", 
          arrayItems , @"items", 
          userID , @"user_id", 
          nil]; 
return mainDictionary; 
+0

は、実際に私はこの部分を作成することができません "アイテム":[{ "ITEM_ID": "10"、 "量": "10" }、{ "ITEM_ID": "11"、 "quantity": "10" }] – iOSGeek

+0

あなたは私の答えを確認できます:) –

+0

私は無効なjsonを返します。 – iOSGeek

答えて

2

無効なJSONを生成JSONを作成するための私のコードです。

NSMutableArray *arrayItems = [NSMutableArray new]; 
[arrayItems addObject: dic]; 

NSDictionary *dic = @{ 
     "item_id": "10", 
        "quantity": "10" 
    }; 

ようNSMutableArrayの内のオブジェクトのこれらのタイプを追加します。お好みの商品辞書のオブジェクトと項目に1つのアレイを取らなければならない

:あなたのケースでは

このようにして、この配列に複数の辞書を追加することができます。上記のすべてのキー値のペアを保持する別の辞書を取ることができます:

NSMutableDictionary *dicMain = [NSMutableDictionary new]; 
[dicMain setValue:"APIKey" forKey:"api_key"]; 
[dicMain setObject:arrayItems forKey:"items"]; // add items array in dictionary 

などすべてのキーと値のペアを設定しています。

この

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:[NSDictionary dictionaryWithDictionary:dict] options:0 error:nil]; 

、これはあなたを助けるかもしれない。この

[request setHTTPMethod:@"POST"]; 
[request setHTTPBody:objData]; 

希望body.like要求として、このデータを設定を使用してJSONデータにこの辞書を変換します。 :)

+0

無効なjsonを返しますNSMutableArray * arrayItems = [NSMutableArray new]; for(int i = 0; i iOSGeek

+0

この行をチェックアウトするNSDictionary * dic = @ {数量:@ "数量"、item.itemID:@ "item_id"}; NSDictionary * dic = @ {@ "quantity":quantity、@ "item_id":item.itemID};でこの行のキーをこの形式で最初に置きます。 –

+0

アプリケーションがクラッシュするか、期待通りにアレイを取得できませんか?私はその正確な問題を知りませんでした。何か詳細に説明していただけますか? –

-1
NSDictionary *dic = @{ 
    @"api_key": @"APIKey", 
    @"items": @[@{ 
     @"item_id": @"10", 
     @"quantity": @"10" 
    }, @{ 
     @"item_id": @"11", 
     @"quantity": @"10" 
    }], 
    @"user_id": @"UserID", 
    @"user_address": @"address", 
    @"user_number": @"number" 
} 
関連する問題