【问题标题】:Find index of element in a JSONArray在 JSONArray 中查找元素的索引
【发布时间】:2014-05-30 07:06:49
【问题描述】:

我从服务器收到如下 JSONObject:

{
   "opOutput":{
      "DISPLAY_VALUES":[
         "Acceptance",
         "Arrive Load Port",
         "Arrive Receipt Point",
         "Arrive Relay Port",
         "Arrive Terminal",
         "Arrived at Delivery Location",
         "Arrived at Pickup Location",
         "Arrived Intermodal Train",
         "At Customs",
         .
         .
         .
         .  


      ],
      "VALUES":[
         "ACCPT",
         "ALPT",
         "ARRP",
         "ARREL",
         "ATRM",
         "QARD",
         "ARPUL",
         "AIMTRN",
         "K",
         .
         .
         .
         .
      ]
   },
   "_returnValue":{
      "TX_TYPE":"SHIPMENT",
      "__DeltaStatus":2,
      "ORG_CODE":"GFM",
      "TX_ID":"11019082"
   },
   "_returnType":"SUCCESS"
}

现在我需要获取 s String s 的显示值,该值等于其中一个值。 即我有字符串“ACCPT”,我需要从 JSONObject 获取“Acceptance”。

我用 DISPLAY_VALUES 和 VALUES 制作了两个 JSONArray 与

JSONObject opoutput=shipmentcodes.getJSONObject("opOutput");
JSONArray event_values=opoutput.getJSONArray("DISPLAY_VALUES");
JSONArray event_codes=opoutput.getJSONArray("VALUES");

其中 shippingcodes 是原始 JSONObject,但我不确定如何进一步处理。有什么建议吗?

【问题讨论】:

  • 为什么不能只遍历 JSONArray,计算索引,然后在找到匹配项时停止?
  • 在 for 循环中遍历 VALUES 数组,直到找到匹配项,然后使用该索引从 DISPLAY_VALUES 中获取正确的显示值。
  • @bstar55 是的,我想我可以做到。我认为可能有一些 JSONArray 方法可以返回给定元素的索引,而无需我们通过循环。

标签: java json arrays


【解决方案1】:

将JSONArray 中的值添加到List 并使用indexOf 方法

JSONArray event_values = opoutput.getJSONArray("DISPLAY_VALUES");
JSONArray event_codes = opoutput.getJSONArray("VALUES");

List<String> valueList = new ArrayList<String>();
List<String> displayList = new ArrayList<String>();
for(int i=0;i<event_codes.length();i++){
        // if both event_values and event_codes are of equal length
        valueList.add(event_codes.getString(i));
        displayList.add(event_values.getString(i));
    }

int index = valueList.indexOf("ACCPT");
String valueToDisplay = displayList.get(index);

然后您可以使用valueToDisplay 来显示您需要的值。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-03
  • 2011-12-16
  • 2013-08-26
  • 2013-07-26
  • 1970-01-01
  • 2015-08-19
相关资源
最近更新 更多