Home > Back-end >  How to retrieve a random element from a JSON array file in Java?
How to retrieve a random element from a JSON array file in Java?

Time:06-13

I have a two JSON files located in the resources package of my maven project. They are files called first-names.json and last-names.json. They both look something like this:

{
   "first_names": [
      "Aaron",
      "Abby",
      "Abigail",
      etc..
   ]
}

My goal with this is I'm making an API that can retrieve a person with random attributes like first name and last name. Each one of these arrays has 10,000 names. How would I go about retrieving a random element these files so I can assign it into my Person object?

Project Structure:

enter image description here

CodePudding user response:

For reading file content from resources folder please refer to:

How do I load a file from resource folder?

What’s the best way to load a JSONObject from a json text file?

Assign file content to corresponding String variables.

Convert JSON string to JSON array then select a random item through names and last names array:

public static void main(String[] args) {
    String namesJsonString = "{\n"  
            "   \"first_names\": [\n"  
            "      \"Aaron\",\n"  
            "      \"Abby\",\n"  
            "      \"Abigail\",\n"  
            "   ]\n"  
            "}";

    String lastNamesJsonString = "{\n"  
            "   \"last_names\": [\n"  
            "      \"last name 1\",\n"  
            "      \"last name 2\",\n"  
            "      \"last name 3\",\n"  
            "   ]\n"  
            "}";
    JSONObject namesJson = null;
    JSONObject lastNamesJson = null;
    try {
        namesJson = new JSONObject(namesJsonString);
        JSONArray namesJsonArray = namesJson.getJSONArray("first_names");

        lastNamesJson = new JSONObject(lastNamesJsonString);
        JSONArray lastNamesJsonArray = lastNamesJson.getJSONArray("last_names");

        int namesArrayLength = namesJsonArray.length();
        int lastNamesArrayLength = lastNamesJsonArray.length();
        for (int i = 0; i < 5; i  ) {
            int randomNameIndex = (int) (Math.random() * namesArrayLength);
            String randomName = namesJsonArray.getString(randomNameIndex);

            int randomLastNameIndex = (int) (Math.random() * lastNamesArrayLength);
            String randomLastName = lastNamesJsonArray.getString(randomLastNameIndex);
            System.out.println(randomName   " "   randomLastName);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

CodePudding user response:

You can use this technique. Pass the file name as the argument to the app:

import javax.json.*;
import java.util.*;
import java.io.*;

public class JsonTest {
    public static void main(String[] args) {
        try (JsonReader in = Json.createReader(new FileReader(args[0]))) {
            JsonArray array = in.readObject().getJsonArray("first_names");
            int arrayLength = array.size();
            Random r = new Random();
            System.out.printf("Your random array element is %s%n", array.getString(r.nextInt(arrayLength)));
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}
  • Related