Java数组的Java等价物

时间:2012-01-10 14:24:05

标签: php android

我需要将一个数组发送到服务器,但我似乎找不到正确的格式。

这是我需要发送的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]

但这是不正确的

3 个答案:

答案 0 :(得分:2)

您应该使用java.util包中的HashMap。有关更多详细信息,请查看API文档;)

答案 1 :(得分: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");

希望您了解如何格式化数组:)

答案 2 :(得分:0)

Java类HashMap应该这样做。使用键值对概念。

以下是实施示例http://www.javadeveloper.co.in/java-example/java-hashmap-example.html