简体   繁体   中英

How to generate a JSON file from elements of an arraylist in random order in Java?

I am trying to generate a JSON file using elements from an arraylist. The JSON file should have 100 objects and i an using a loop to generate them.

package co.pravin;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import java.util.Map;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Random;

import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class JsonParse10000Elements {

    /**
     * @param args
     */
    public static void main(String[] args) throws FileNotFoundException {
        // TODO Auto - generated method stub

        ArrayList<String> names = new ArrayList<String>();
        ArrayList<String> nums = new ArrayList<String>();

        names.add("Pravin");
        names.add("Naren");
        names.add("Sanjay");
        names.add("Kicha");

        nums.add("1");
        nums.add("2");
        nums.add("3");

        Random randomGenerator = new Random();
        String name;
        String num;

        int sizeOfNameArrayList;
        int sizeOfNumArrayList; 

        JSONObject jo = new JSONObject();
        JSONArray ja = new JSONArray();

        int n = 100;
        Map m = new LinkedHashMap(n);

        for (int i = 0; i < n; i++) {

            sizeOfNameArrayList = randomGenerator.nextInt(names.size());
            sizeOfNumArrayList = randomGenerator.nextInt(nums.size());

            name = names.get(sizeOfNameArrayList);
            num = nums.get(sizeOfNumArrayList);

            m.put("name", name);
            m.put("num", num);  

            ja.add(m);

        }


        jo.put("Employess", ja);

        PrintWriter p = new PrintWriter("JsonEg1000Elements.json");
        p.write(jo.toJSONString());

        p.flush();
        p.close();
    }
}

But everytime i run it, only one element is selected and parsed 100 times, instead of 100 random elements. The output looks like this :

{
"Employees": [
    {
        "name": "Naren",
        "num": "2"
    },
    {
        "name": "Naren",
        "num": "2"
    },
    {
        "name": "Naren",
        "num": "2"
    },
    {
        "name": "Naren",
        "num": "2"
    }, ... and so on. 

How can I select 100 elements at random, instead of the same element getting repeated 100 times?

You are editing the same object, because this is above the loop:

Map m = new LinkedHashMap(n);

Moving it to:

for (int i = 0; i < n; i++) {
  Map m = new LinkedHashMap(n);
  // Rest of your code

should work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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