【问题标题】:accessing value from array randomly [closed]随机访问数组中的值[关闭]
【发布时间】:2018-04-06 06:11:15
【问题描述】:
import org.json.JSONObject;
import org.json.JSONArray;
import java.util.Random;


int minimum=0;
String[] code_array = new String[10];
String response= ctx.getPreviousResult().getResponseDataAsString();
log.info(response);
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("options");
Integer opt_count= jsonArray.length();
vars.put('count',Integer.toString(opt_count));
if(opt_count > 1)
{
for (int a= 0; a < opt_count; a++)
{
    code_array[a] .add(jsonArray.getJSONObject(a).getString("code"));
    log.info(code_array[a]);
    JSONArray  new_array= jsonArray.getJSONObject(a).getJSONArray("values");
    log.info(new_array);
    int Value_count =  new_array.size();
    vars.put('VALUE_COUNT',Integer.toString(Value_count));
    if(Value_count > 1)
    {
        Random r= new Random();
        int random_value = r.nextInt(Value_count - minimum) + minimum;
        vars.put('random_value1',random_value);
        Integer FValue= 
  new_array.getJSONObject(random_value).getString("value");
        vars.put('FValue',Integer.toString(FValue));
    }
   }

}
else{

      vars.put('Attribute','First Attribute');

 }

JSON 在这里:Parsing json objects(multiple) using groovy

我需要达到同样的效果:options[0].values[0].value

上面的参数 [0] on value 是硬编码的。我想随机化并获得价值。

【问题讨论】:

  • 您真正遇到的问题是什么?想出一个随机索引?检索值?
  • @Stultuske 两者。
  • 有什么帮助吗?您可以尝试非随机读取数组吗?我们将在该部分添加随机性。
  • @AxelH ,我需要在 Java 中实现这一点。 stackoverflow.com/questions/49650288/…
  • 还有……有什么问题?你试过什么?你在问什么 ?你在期待什么?如果您真的认为我们来这里是为了完成您的工作,那么您没有阅读常见问题解答...edit 您的问题与 SO 的范围相匹配,我将在那里提供帮助。现在,没有您的努力,只有广泛的要求。

标签: java arrays json


【解决方案1】:

如果我正确地解决了您的问题,那么您可以尝试这样的事情..

public static int getRandomIndex(int min, int max) {

    Random r = new Random();
    return r.nextInt((max - min) + 1) + min;

}


JSONObject jsonObject1 = Array.getJSONObject(getRandomIndex(0,length_of_JSONArray));

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-01
  • 2019-07-18
  • 1970-01-01
  • 1970-01-01
  • 2021-03-18
  • 2021-01-07
  • 1970-01-01
相关资源
最近更新 更多