Java 查找 JSONArray 中元素的索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23948955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 09:18:34  来源:igfitidea点击:

Find index of element in a JSONArray

javajsonarrays

提问by Kartik_Koro

I receive a JSONObject from server that is as follows:

我从服务器收到一个 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"
}

Now I need to get the display value for s String s that is equal to one of the values. i.e I have string "ACCPT" and i need to get "Acceptance" from the JSONObject.

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

I've made two JSONArrays with DISPLAY_VALUES and VALUES with

我用 DISPLAY_VALUES 和 VALUES 制作了两个 JSONArrays

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

where shipmentcodes is the original JSONObject, but I'm unsure about how to proceed further. Any tips?

其中装运代码是原始 JSONObject,但我不确定如何进一步处理。有小费吗?

采纳答案by MjZac

Add the values from JSONArrayto a Listand use the indexOfmethod

将值添加JSONArray到 aList并使用该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);

You can then use valueToDisplayfor displaying the value you need.

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