JSONArray的问题随机化

时间:2017-10-02 17:38:28

标签: java json random

我正试图以这种方式随机化JSON数组:

private static JSONArray getJSONArray(Context context) {
    JSONArray myJSONarr=new JSONArray();
    JSONArray myRandomizedJSONarr=new JSONArray();
    try
    {
        InputStream is = context.getAssets().open("chineesecardsdata.json");
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        String resultJson = new String(buffer, "UTF-8");

        try {
            JSONObject myJSONObject=new JSONObject(resultJson);
            myJSONarr=myJSONObject.getJSONArray("data");
            Log.d("mainActLog","Array before random: "+myJSONarr.toString());
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }
    }
    catch(
            IOException e) {        
    }

    try {
        ArrayList<Integer> intArr1 = new ArrayList<>(myJSONarr.length());
        for (int i = 0; i < myJSONarr.length(); i++) {
            intArr1.add(i);
        }
        Collections.shuffle(intArr1);
        for (int i = 0; i < intArr1.size(); i++) {
            myRandomizedJSONarr.put(i, myJSONarr.getJSONObject(intArr1.get(i)));
            if (i == (myJSONarr.length() - 1))
                break;
        }
        Log.d("mainActLog","Array after random: "+myRandomizedJSONarr.toString());
    }
    catch (JSONException e){}
    return myRandomizedJSONarr;
}

因此,不仅JSON对象是随机的,还有键和值。 我的意思是,我有一个像这样的数组:

  

[   { “ID”: “0”, “象形文字”: “水”, “拼音”: “Shuǐ”, “pinyin_num”: “Shui3”, “俄语”:[ “вода”], “HSK”: “1” },   { “ID”: “1”, “象形文字”: “人”, “拼音”: “REN”, “pinyin_num”: “Re2n”, “俄语”:[ “человек”], “HSK”: “1” },   { “ID”: “2”, “象形文字”: “日”, “拼音”: “RI”, “pinyin_num”: “的R 14”, “俄语”:[ “день”], “HSK”: “1” },   { “ID”: “3”, “象形文字”: “不”, “拼音”: “BU”, “pinyin_num”: “BU4”, “俄语”:[ “нет”], “HSK”: “1” },   { “ID”: “4”, “象形文字”: “少”, “拼音”: “Shǎo”, “pinyin_num”: “Sha3o”, “俄语”:[ “мало”], “HSK”: “1” }]

随机化后,它看起来像这样

  

[{ “ID”: “2”, “象形文字”: “日”, “拼音”: “RI”, “pinyin_num”: “的R 14”, “俄语”:[ “день”], “HSK” : “1”},   { “ID”: “2”, “象形文字”: “日”, “拼音”: “RI”, “pinyin_num”: “的R 14”, “俄语”:[ “день”], “HSK”: “1” },   { “ID”: “4”, “象形文字”: “少”, “拼音”: “Shǎo”, “pinyin_num”: “Sha3o”, “俄语”:[ “мало”], “HSK”: “1” },   { “ID”: “3”, “象形文字”: “不”, “拼音”: “BU”, “pinyin_num”: “BU4”, “俄语”:[ “нет”], “HSK”: “1” },   { “ID”: “2”, “象形文字”: “日”, “拼音”: “RI”, “pinyin_num”: “的R 14”, “俄语”:[ “день”], “HSK”: “1” }]

1 个答案:

答案 0 :(得分:0)

为什么不直接将数组洗牌?

List<JSONObject> myList = new ArrayList<JSONObject>();
for(int i = 0; i < myJSONarr; i++){    
    myList.add(myJSONarr.getJSONObject(i));
}
Collections.shuffle(myList);