简体   繁体   English

如何从JSON数组中获取随机对象

[英]How to get random objects from a JSON array

This JSONAray: 此JSONAray:

"cows": [
    {
      "age": 972,
      "name": "Betty"
      "status": "publish",
      "sticky": "pregnant"
    },
    {
      "age": 977,
      "name"; "Kate"
      "status": "publish",
      "sticky": "heat"
    },
    {
      "age": 959,
      "name": "Julie"
      "site_age": 63178480,
      "sticky": "Nursing"
    },
    ...
 }

that contains 20 objects. 包含20个对象。 What I wanted is this: get 3 random objects out of the 20. And the ages of any of the three won't be a certain number say 961. 我想要的是:从20个对象中取出3个随机对象。这三个对象中任何一个的年龄都不会是一个确定的数字,例如961。

Currently this what I am doing: 目前,我正在做什么:

private void parseCowsReq(JSONObject array) {
         try {
             for (int i = 0; i < 3; i++) {
                 int randumNum = getRandomCow(array);
                 JSONObject jsonObject = array.getJSONObject(randumNum);
                 String cowName = jsonObject.getString("name");
                 String cowStatus = jsonObject.getString("status");
                 Log.d(TAG, "Cow name is " + cowName + "cow Status is " + cowStatus);
             }

         } catch (JSONException e) {
             e.printStackTrace();
         }
  }

  private int getRandomCow(JSONArray jsonArray) {
          int length = jsonArray.length();
          int[] array;
          array = new int[length-1];
          int rnd = new Random().nextInt(array.length);
          return array[rnd];
  }

There are of issues with this code. 此代码存在问题。

  1. I don't know how to ensure that the object gotten in line JSONObject jsonObject = array.getJSONObject(randumNum); 我不知道如何确保在JSONObject jsonObject = array.getJSONObject(randumNum);行中获取对象JSONObject jsonObject = array.getJSONObject(randumNum); won't have an age of 961 不会有961岁
  2. The random number gotten is always 0 随机数始终为0

    Please do you have any idea how this can be done? 请问您如何做到这一点?

you can do it with this: 您可以这样做:

public ArrayList<Integer> getRandomObject(JSONArray jsonArray, int indexesWeeNeed){
    Random rn = new Random();
    Set<Integer> generated = new LinkedHashSet<>();
    while(generated.size() < indexesWeeNeed){
        int index = rn.nextInt(10);
        JSONObject jsonObject = (JSONObject) jsonArray.get(index);
        int age = jsonObject.getInt("age");
        if(age<961) {
            generated.add(index);
        }
    }
    ArrayList<Integer> arrayList = new ArrayList<>();
    arrayList.addAll(generated);
    return arrayList;
}

Well firstly, load the objects: 首先,加载对象:

JSONArray array = /* your array */;

Next, we need a method to retrieve 3 unique objects from the JSONArray (which is actually a List ). 接下来,我们需要一种从JSONArray (实际上是List )中检索3个唯一对象的方法。 Let's shuffle the indexes of the json array, so that we don't end up having to repeatedly generate duplicates: 让我们重新整理json数组的索引,以免最终不必重复生成重复项:

public Stream<JSONObject> randomObjects(JSONArray array, int amount) {
    if (amount > array.size()) {
        //error out, null, return array, whatever you desire
        return array;
    }
    List<Integer> indexes = IntStream.range(0, array.size()).collect(Collectors.toList());
    //random, but less time generating them and keeping track of duplicates
    Collections.shuffle(indexes);
    Set<Integer> back = new HashSet<>();
    Iterator<Integer> itr = indexes.iterator();
    while (back.size() < amount && itr.hasNext()) {
        int val = itr.next();
        if (array.get(val).getInt("age") != 961) { //or any other predicates
            back.add(val);
        }
    }
    return back.stream().map(array::get);
}

Using this, we can select the three objects from the list and utilize them how we wish: 使用此方法,我们可以从列表中选择三个对象,并按我们希望的方式利用它们:

randomObjects(array, 3).map(o -> o.getInt("age")).forEach(System.out::println);
//972
//977
//952

When I said "or any other predicates, you can pass those as well via the method: 当我说“或任何其他谓词时,您也可以通过方法传递这些谓词:

public Stream<JSONObject> randomObjects(..., Predicate<Integer> validObject) {
    //...
    int val = itr.next();
    if (validObject.test(val)) {
        back.add(val);
    }
    //...
}

Which would mean you could change the blacklisting per method call: 这意味着您可以更改每个方法调用的黑名单:

Stream<JSONObject> random = randomObjects(array, 3, val -> array.get(val).getInt("age") != 961);

One part that's messed up is when you call 麻烦的是您打电话时
Random().nextInt(array.length); 。随机()nextInt(array.length);
array.length is the new array you just created. array.length是您刚创建的新数组。 You need to perform the function on the existing array: 您需要在现有阵列上执行该功能:
Random().nextInt(jsonArray) 随机的()。nextInt(JSONArray),其中
to get a random number other than zero. 以获得非零的随机数。

As for ensuring you don't get a certain age, I'd suggest breaking up the code to not call the getRandomCow(array) function inside of the for loop. 为了确保您没有达到一定的年龄,我建议您分拆代码,不要在for循环内调用getRandomCow(array)函数。 When you retrieve a cow, check the name doesn't match, check the age, and if it works, keep it. 取回一头母牛时,请检查名称是否匹配,检查年龄,如果可行,请保留该名称。 If not get another cow. 如果没有得到另一头牛。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM