在JSONArray中查找元素的索引

时间:2014-05-30 07:06:49

标签: java json arrays

我从服务器收到一个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创建了两个JSONArrays 与

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

其中,shippingcodes是原始的JSONObject,但我不确定如何继续进行。有什么提示吗?

1 个答案:

答案 0 :(得分:2)

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来显示所需的值。