【发布时间】: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 的范围相匹配,我将在那里提供帮助。现在,没有您的努力,只有广泛的要求。