2012-01-10 33 views
0

我需要發送一個數組到一個服務器,但我似乎無法找到正確的格式。一個PHP數組的Java Equivilent

這裏是PHP的等價,我需要發送

array(
     'interest' => 1, 
     'charity' => 590, 
     'items' => array(
       array(
         'cart_item_id' => 11197, 
         'message' => '', 
         'aid' => 174 
       ), 
     ), 
   ); 

我試圖讓namevaluepairs中把我的數據 - 這裏就是我想

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
    if (interest == true) { 
     nameValuePairs.add(new BasicNameValuePair("interest", "1"));     
    } else { 
     nameValuePairs.add(new BasicNameValuePair("interest", "0"));  
    } 
    nameValuePairs.add(new BasicNameValuePair("charity", String.valueOf(charityId))); 
    int len = cartItems.size(); 
    for (int i = 0; i < len; ++i) { 
     nameValuePairs.add(new BasicNameValuePair("items[" + String.valueOf(i) + "]" + "[cart_item_id]", String.valueOf(cartItems.get(i).cartItemId))); 
     nameValuePairs.add(new BasicNameValuePair("items[" + String.valueOf(i) + "]" + "[message]", cartItems.get(i).message)); 
     nameValuePairs.add(new BasicNameValuePair("items[" + String.valueOf(i) + "]" + "[aid]", String.valueOf(cartItems.get(i).addressId))); 
    } 

這是不正確壽。一如往常的任何幫助深表感謝

編輯

爲了澄清這是我的應用程序向服務器發送

[interest=0, charity=1878, items[0][cart_item_id]=14498, items[0][message]=, items[0][aid]=315, items[1][cart_item_id]=14499, items[1][message]=, items[1][aid]=318] 

但是這是不正確

+0

的想法,我想你在for循環中,首先檢查名稱和值正確的按照你祝使用System.out.prinln創建問題() ;,請注意,您必須將字符串值發送到服務器 – 2012-01-10 14:28:22

+0

該應用運行正常。它將詳細信息發送到服務器,但它們的格式不正確。我發送字符串 – jiduvah 2012-01-10 14:31:45

回答

1

使用HashMap<Object,Object>,然後當你要添加的子陣列:

array(
      'cart_item_id' => 11197, 
      'message' => '', 
      'aid' => 174 
) 

剛加入新HashMap<String,String>到您的超級HashMap<Object,Object>:邏輯會像這樣:

HashMap parentMap = new HashMap(); HashMap subMap = new HashMap();

// put params into parentMap 
parentMap.put("key1", "this is a string value"); 
parentMap.put("key2", 45); 
parentMap.put("key3", new Date()); 

subMap.put("card_item_id", ""+11197); 
subMap.put("message", "this is a message from subMap"); 
parentMap.put("items", subMap); 

//get the subMap from the parentMap like this 
HashMap<String, String> copySubMap = (HashMap<String, String>) parentMap.get("items"); 

希望,你是如何格式化你的陣列:)

+0

這使得它更加清晰,謝謝。但是,該代碼不會編譯。我得到的錯誤 方法add(字符串,字符串)是未定義的類型HashMap <對象,對象> 是應該把,而不是添加:) – jiduvah 2012-01-10 15:08:33

+0

我剛剛寫代碼沒有使用Eclipse IDE,所以你得到的問題只是一個演員或其他東西。關鍵是你已經知道如何解決你的問題。很高興聽到它:) – Houcine 2012-01-10 15:13:29

+0

是的,它讓我現在編碼一個hashmap的問題現在 – jiduvah 2012-01-10 15:22:06

2

你應該在包中使用該HashMap java.util中。看看API文檔的更多細節;)

+0

感謝您的輸入,但我正在尋找如何真正格式化數組。我會研究哈希映射,因爲它看起來像是正確的類,但它不能幫助我解決數組應該如何格式化的問題。 – jiduvah 2012-01-10 14:35:45