douying4909 2012-01-10 14:24
浏览 25
已采纳

Java数组的Java等价物

I need to send an array to a server but I cannot seem to find the correct formatting for it.

Here is the php equivalent that I need to send

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

I am trying to get send my data in nameValuePairs - here is what I am trying

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)));
    }

This is incorrect tho. As always any help is much appreciated

Edit

For clarification this is what my app sends to the server

[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]

but that is incorrect

  • 写回答

3条回答 默认 最新

  • dongwei4096 2012-01-10 14:55
    关注

    use a HashMap<Object,Object> , and then when you want to add the sub array :

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

    just add a new HashMap<String,String> into your Super HashMap<Object,Object> : the logic will be something like this:

    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");
    

    hope that you got the idea of how formatting your array :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序