Java variable names cannot be constructed dynamically.

I don't know how no one has answered this yet but here you are.

JSONObject objects = new JSONObject[10];
for(int i = 0 ; i < objects.length ; i++) {
    objects[i] = new JSONObject();
}

JSONObject o = objects[2]; // get the third one

Arrays are not dynamically resizable. You should use an appropriate List implementation if you need such behavior. If you want to access the elements by name, you can also use a Map.

Map<String, JSONObject> map = new HashMap<>();
for(int i = 0 ; i < 10 ; i++) {
    map.put("tempName" + i, new JSONObject());
}

JSONObject o = map.get("tempName3"); // get the 4th created (hashmaps don't have an ordering though)
Answer from Sotirios Delimanolis on Stack Overflow
Discussions

How to create a json array with multiple objects java spring boot - Stack Overflow
I have created the user with most comments and highest rated game fine, but stuck on how to create the json array for the average_likes_per_game. I want to make something that looks like this: { ... More on stackoverflow.com
🌐 stackoverflow.com
Multiple Objects from one Json file using Jackson
Something that is done sometimes is to have one JSON object per line, read the file line by line and then parse those lines individually into objects. But just creating a JSON array like u/captain_breakdance posted is probably easier. More on reddit.com
🌐 r/javahelp
2
1
September 20, 2018
java - Writing of values to multiple JSON objects - Stack Overflow
I am building a quiz application where the user can answer multiple questions by choosing one option out of a, b, c, d. Right now, when the user is entering his answer to a question, the answer is More on stackoverflow.com
🌐 stackoverflow.com
Best way to create multiple JSON Elements?
Trying to create a JSON structure in FileMaker like this: { "Cars" : "[VW, GM, Other]", "First_Name" : "Alan", "Last_Name" : "Jones" } { "Cars" : "[Ford, Lexus, BMW]", "First_Name" : "John", "Last_Name" : "Smith" } I've tried two approaches, but both just give me the last JSON element. More on the.fmsoup.org
🌐 the.fmsoup.org
19
0
June 3, 2020
🌐
CodeProject
codeproject.com › Questions › 1164374 › How-to-add-multiple-object-in-JSON-object-array
How to add multiple object in JSON object/array?
Do not try and find the page. That’s impossible. Instead only try to realise the truth - For those who code; Updated: 1 Jul 2007
Top answer
1 of 1
2
String.valueOf(gameService.convertLikesToJsonArray(averageLikesPerGame)); 

You are making this a single value in the json, instead of it being actual json. That's why it's all escaped in your JSON output. You also haven't shown your pretty print method, so can't comment on the output of that. Try

    //Use object instead of String as you want nested objects in output
    Map<String, Object> report = new HashMap<>();

    String highestRankedGame = gameService.findHighestRatedGame();
    String userWithMostComments = gameService.findUserWithMostComments();
    Map<String,String> averageLikesPerGame = gameService.findAverageLikesPerGame();

    report.put("highest_rated_game",highestRankedGame);
    report.put("user_with_most_comments", userWithMostComments);
   //Add averageLikesPerGame directly to report without modifying
    report.put("average_likes_per_game",averageLikesPerGame.entrySet());

    String jsonReport = gameService.convertReportToJson(report);

    return jsonReport;

And

public String convertReportToJson(Map<String, Object> report) {

    ObjectMapper mapper = new ObjectMapper();
    String jsonArray = null;
    try {
        //Don't need Gson, can use writerWithDefaultPrettyPrinter with Jackson which 
        //You are already using
        jsonArray = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(report);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
    return jsonArray;
}

If you want mapped values in the array with labels then you could do something like this

    List<Map<String,String>> labelledAvgLikesPerGame =
            averageLikesPerGame.entrySet().stream()
                    .map( entry ->
                           //Needs java 9+ for ofEntries
                           //You'll need to make new HashMap,put + return
                           // for java 8
                            Map.ofEntries(
                                    Map.entry("title", entry.getKey()),
                                    Map.entry("average_likes", entry.getValue())
                            )).collect(Collectors.toList());

    report.put("highest_rated_game",highestRankedGame);
    report.put("user_with_most_comments", userWithMostComments);
    report.put("average_likes_per_game",labelledAvgLikesPerGame);
Top answer
1 of 2
2

You need to use a json library like org.json, create a JSONArray and fill it with JSONObjects, Assuming I understand the structure correctly, what you're referring to as Object o is actually a Map.Entry<String, String> , which you can use to get a key and a value, I believe the key will have the question (Q1, Q2, Q3...) which you can use to add objects into the JSONArray

JSONArray arr = new JSONArray();
    
for (Map.Entry<String, String> o: entry) {
    String answer = askUser();
    
    JSONObject answerObject = new JSONObject();
    answerObject.put(o.getKey(), answer);
    
    arr.put(answerObject);
}

System.out.println(arr.toString(4));

output:

[
    {"Q1": "c"},
    {"Q2": "a"},
    {"Q3": "b"},
    {"Q4": "b"},
    {"Q5": "c"}
]
2 of 2
1

JSON is file format that allow to transfer objects between different programs, even when they use different programming languages. If you really want the solution in such form, you need to use some library that provides JSON service (I recommend GSON from myself). The code from the solution in form you want: Firstly you need to make a class (e.g. Answers):

public class Answers {
    String Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q10, Q11, Q12, Q13, Q14, Q15;

    public void setQ1(String q1) {
        Q1 = q1;
    }

    public void setQ2(String q2) {
        Q2 = q2;
    }

    public void setQ3(String q3) {
        Q3 = q3;
    }

    public void setQ4(String q4) {
        Q4 = q4;
    }

    public void setQ5(String q5) {
        Q5 = q5;
    }

    public void setQ6(String q6) {
        Q6 = q6;
    }

    public void setQ7(String q7) {
        Q7 = q7;
    }

    public void setQ8(String q8) {
        Q8 = q8;
    }

    public void setQ9(String q9) {
        Q9 = q9;
    }

    public void setQ10(String q10) {
        Q10 = q10;
    }

    public void setQ11(String q11) {
        Q11 = q11;
    }

    public void setQ12(String q12) {
        Q12 = q12;
    }

    public void setQ13(String q13) {
        Q13 = q13;
    }

    public void setQ14(String q14) {
        Q14 = q14;
    }

    public void setQ15(String q15) {
        Q15 = q15;
    }
}

Then you need to make an object of class Answers which will handle answers and convert it to JSON (using GSON for example):

Answers answers = new Answers();
    //somehow set the values (maybe by using Scanner.in?)
        answers.setQ1("YES");
        answers.setQ2("YES");
        answers.setQ3("NO");
        answers.setQ4("NO");
        answers.setQ5("dog");
        answers.setQ6("Giraffe");
        answers.setQ7("Gson");
        answers.setQ8("Java");
        answers.setQ9("CSS");
        answers.setQ10("NO");
        answers.setQ11("Maven");
        answers.setQ12("dog");
        answers.setQ13("Elephant");
        answers.setQ14("Gson");
        answers.setQ15("No");
    //using Gson
        String json_file;
        Gson g = new Gson();
        json_file = g.toJson(answers);
    // to file
        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter("answers.json"));
            writer.write(json_file);

            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

.json file:

{
  "Q1": "YES",
  "Q2": "YES",
  "Q3": "NO",
  "Q4": "NO",
  "Q5": "dog",
  "Q6": "Giraffe",
  "Q7": "Gson",
  "Q8": "Java",
  "Q9": "CSS",
  "Q10": "NO",
  "Q11": "Maven",
  "Q12": "dog",
  "Q13": "Elephant",
  "Q14": "Gson",
  "Q15": "No"
}

However, in my opinion the code that satisfy your idea is too complicated and I highly recommend to reconsider it. Maybe it would be better to use Answers class with some informations about the person that plays the quiz and much cleaner String Array of answers instead of different variables for each one. Programmer should always try to find a way to optimize, clean and simplify the solution. As an example:

public class Answers {
    int id;
    String name;
    String surname;
    String[] answer;

    public void setId(int id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public Answers() {
        answer = new String[15];
    }
}

main body:

Answers answers = new Answers();
    //somehow set the values (maybe by using Scanner.in?)
        answers.setId(1);
        answers.setName("John");
        answers.setSurname("Baker");
        answers.answer[0] = "YES";
        answers.answer[1] = "YES";
        answers.answer[2] = "NO";
        answers.answer[3] = "NO";
        answers.answer[4] = "Elephant";
        answers.answer[5] = "Java";
        answers.answer[6] = "Maven";
        answers.answer[7] = "CSS";
        answers.answer[8] = "bash";
        answers.answer[9] = "quiz";
        answers.answer[10] = "dog";
        answers.answer[11] = "coffee";
        answers.answer[12] = "tea";
        answers.answer[13] = "YES";
        answers.answer[14] = "Borneo";
    //using Gson
        String json_file;
        Gson gson = new Gson();
        json_file = gson.toJson(answers);
    // to file
        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter("answers.json"));
            writer.write(json_file);

output .json:

{
  "id": 1,
  "name": "John",
  "surname": "Baker",
  "answer": [
    "YES",
    "YES",
    "NO",
    "NO",
    "Elephant",
    "Java",
    "Maven",
    "CSS",
    "bash",
    "quiz",
    "dog",
    "coffee",
    "tea",
    "YES",
    "Borneo"
  ]
}

You can add some code for input of answers (I mean to make them be taken from keyboard or what you want), but I redirect to google. Be creative!

🌐
Fmsoup
the.fmsoup.org › questions
Best way to create multiple JSON Elements? - Questions - the.fmsoup.org - Independent FileMaker Forum. Help, Discussions & Answers for Developers and Users
June 3, 2020 - Trying to create a JSON structure in FileMaker like this: { "Cars" : "[VW, GM, Other]", "First_Name" : "Alan", "Last_Name" : "Jones" } { "Cars" : "[Ford, Lexus, BMW]", "First_Name" : "John", "Last_Name" : "Smith…
Find elsewhere
Top answer
1 of 2
1

The line you want

{"1":"{\"id\":\"1\"}"**,**"2":"{\"id\":\"2\"}"**,**"3":"{\"id\":\"3\"}"}

isn't legal either, I assume you mean (at least) something like this:

{"1":"{\"id\":\"1\"}","2":"{\"id\":\"2\"}","3":"{\"id\":\"3\"}"}

Note that this is not a JSON array, it's an object with string fields respectively called 1 2 and 3 that happen to contain JSON syntaxed string values. Although not illegal, it's highly questionable you actually want that

Now, could it be that you mean

{"1":{"id":"1"},"2":{"id":"2"},"3":{"id":"3"}}

Still an object but with object fields respectively called 1 2 and 3, where the object has just 1 field called id? Anyways (disclaimer: not an org.json library user myself - see below - so not giving any guarantees wrt the accuracy of the code :) ) :

// Create the outer container
JSONObject outer = new JSONObject();

// Create a container for the first contained object
JSONObject inner1 = new JSONObject();
inner1.put("id",1);
// and add that to outer
outer.put("1",inner1);

// Create a container for the second contained object
JSONObject inner2 = new JSONObject();
inner2.put("id",2);
// and add to outer as well
outer.put("2",inner2);

// Create a container for the third contained object
JSONObject inner3 = new JSONObject();
inner3.put("id",3);
// and add that to outer
outer.put("3",inner3);

// at this point

outer.toString()

// should return the JSON String from my last step.

if you actually want it to be an array, you need to put the objects in a JSONArray, and wrap that array as a named field inside an object. The end result will look more or less like this:

{"data": [{"id":"1"},{"id":"2"},{"id":"3"}]}

Code for the inner objects is the same as above, but there's a new layer (the array) between the inner and outer object:

JSONArray middle = new JSONArray();
...
middle.add(inner1);
...
middle.add(inner2);
...
middle.add(inner3);
...
outer.put("data",middle);

Still not sure if that's what you actually want, but I think it's a first step towards a solution. That being said, I would recommend you to switch to a nicer JSON Java library than the one from json.org you are apparently using. Look here for some feedback on different libraries that are available, for my projects I've been using Jackson since quite some time now and I'm very happy with it, but the SO question I linked to talks about several other, excellent alternatives.

2 of 2
0

You should write both objects, as below:

    write.write(vjo.toString());
    write.newLine();
    write.write(conb.toString());
    write.newline();
    write.flush();
    write.close();
🌐
CodeSignal
codesignal.com › learn › courses › handling-json-files-with-java › lessons › creating-and-writing-json-data-with-java-using-jackson
Creating and Writing JSON Data with Java
Here are the key steps to move from structured data to a JSON object: Define Classes: Set up Java classes to represent the hierarchical structure of your JSON data. This involves identifying the main data entities and their relationships. Create Instances: Instantiate these classes and populate ...
🌐
Medium
samedesilva.medium.com › how-to-create-a-nested-json-object-payload-with-an-array-using-java-map-and-pass-it-as-the-payload-2aa0611fa2b3
How to create a Nested JSON Object payload with an Array using Java Map and pass it as the payload…
December 13, 2023 - import com.google.gson.JsonArray; import com.google.gson.JsonObject; public class JsonCreation { public JsonObject jsonBodyCreationToExecuteSyntheticAlert(String monitorId) { // Create the main JSON object JsonObject mainJsonObjectPayload = new JsonObject(); // Create the "monitors" array JsonArray monitorsArray = new JsonArray(); // Create a monitor object JsonObject monitorObject = new JsonObject(); monitorObject.addProperty("monitorId", monitorId); // Add the monitor object to the monitors array monitorsArray.add(monitorObject); // Add the monitors array to the main JSON object mainJsonObjectPayload.add("monitors", monitorsArray); return mainJsonObjectPayload; } }
🌐
Stack Overflow
stackoverflow.com › questions › 37175548 › how-do-i-create-multiple-objects-with-data-from-json-using-gson-java
How do I create multiple objects with data from JSON using gson (Java)? - Stack Overflow
I used http://pojo.sodhanalibrary.com/ to convert it into java classes. From there I have a group, ebayAPI, image_img, bold_price, vip_link, and data classes. I'm lost on how I can iterate through the different items in the "group" to pull their price and links. For instance, when I do this: EbayAPI ebayAPI = gson.fromJson(json, EbayAPI.class); Vip_link link = gson.fromJson(json, Vip_link.class);
Top answer
1 of 16
66

If you want a new object with two keys, Object1 and Object2, you can do:

JSONObject Obj1 = (JSONObject) jso1.get("Object1");
JSONObject Obj2 = (JSONObject) jso2.get("Object2");
JSONObject combined = new JSONObject();
combined.put("Object1", Obj1);
combined.put("Object2", Obj2);

If you want to merge them, so e.g. a top level object has 5 keys (Stringkey1, ArrayKey, StringKey2, StringKey3, StringKey4), I think you have to do that manually:

JSONObject merged = new JSONObject(Obj1, JSONObject.getNames(Obj1));
for(String key : JSONObject.getNames(Obj2))
{
  merged.put(key, Obj2.get(key));
}

This would be a lot easier if JSONObject implemented Map, and supported putAll.

2 of 16
32

In some cases you need a deep merge, i.e., merge the contents of fields with identical names (just like when copying folders in Windows). This function may be helpful:

/**
 * Merge "source" into "target". If fields have equal name, merge them recursively.
 * @return the merged object (target).
 */
public static JSONObject deepMerge(JSONObject source, JSONObject target) throws JSONException {
    for (String key: JSONObject.getNames(source)) {
            Object value = source.get(key);
            if (!target.has(key)) {
                // new value for "key":
                target.put(key, value);
            } else {
                // existing value for "key" - recursively deep merge:
                if (value instanceof JSONObject) {
                    JSONObject valueJson = (JSONObject)value;
                    deepMerge(valueJson, target.getJSONObject(key));
                } else {
                    target.put(key, value);
                }
            }
    }
    return target;
}



/**
 * demo program
 */
public static void main(String[] args) throws JSONException {
    JSONObject a = new JSONObject("{offer: {issue1: value1}, accept: true}");
    JSONObject b = new JSONObject("{offer: {issue2: value2}, reject: false}");
    System.out.println(a+ " + " + b+" = "+JsonUtils.deepMerge(a,b));
    // prints:
    // {"accept":true,"offer":{"issue1":"value1"}} + {"reject":false,"offer":{"issue2":"value2"}} = {"reject":false,"accept":true,"offer":{"issue1":"value1","issue2":"value2"}}
}
Top answer
1 of 2
2

Use this code and Enjoy :)

private void createJsonStructure() {

    try
    {
        JSONObject rootObject = new JSONObject();

        JSONArray carArr = new JSONArray();
        for (int i = 0; i < 2 ; i++)
        {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("CarId", "123");
            jsonObject.put("Status", "Ok");
            carArr.put(jsonObject);
        }
        rootObject.put("Car", carArr);


        JSONArray motorArr = new JSONArray();
        for (int i = 0; i < 2 ; i++)
        {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("MotorId", "123");
            jsonObject.put("Status", "Ok");
            motorArr.put(jsonObject);
        }
        rootObject.put("Motor", motorArr);


        JSONArray busArr = new JSONArray();
        for (int i = 0; i < 2 ; i++)
        {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("BusId", "123");
            jsonObject.put("Status", "Ok");
            busArr.put(jsonObject);
        }
        rootObject.put("Bus", busArr);

        Log.e("JsonObject", rootObject.toString(4));

    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
}
2 of 2
1
    JSONObject motorObject = new JSONObject();
    JSONObject busObject = new JSONObject();
    JSONObject carObject = new JSONObject();
    JSONObject wholeObject =new JSONObject();

    JSONArray motorArray = new JSONArray();
    JSONArray busArray = new JSONArray();
    JSONArray carArray = new JSONArray();

    motorArray.put(motorTracks.getJSONObject());
    busArray.put(buss.getJSONObject());
    carArray.put(car.getJSONObject());

    try
    {
        wholeObject.put("Motor",motorArray);
        wholeObject.put("Bus",busArray);
        wholeObject.put("Car",carArray);
        System.out.println(wholeObject);
    }
    catch (JSONException e)
    {
        e.printStackTrace();
    }
🌐
Quora
quora.com › How-can-we-write-a-JSON-file-with-nested-objects-in-Java
How can we write a JSON file with nested objects in Java? - Quora
Answer (1 of 2): Few Step’s you need to follow :- 1. First have on parent class which hold sub class and their ref it must be some POJO class. 2. Now set the all field value to parent class . 3. Now use any api like jackson,json,gson etc to convert parent class into nested json .
🌐
Stack Overflow
stackoverflow.com › questions › 40430564 › how-to-get-java-to-read-json-string-with-multiple-objects-in-it
jackson - How to get java to read JSON String with multiple objects in it? - Stack Overflow
public class UserTest { public static void main(String[] args) throws JSONException{ String jsonStr = "{" + "\"Names\":[{\"field\":\"John\"," + "\"value\":\"3\"},{" + "\"field\":\"Ali\"," + "\"value\":4 }]}"; ObjectMapper mapper = new ObjectMapper(); try { System.out.println("before obj creation"); SelectList testObject = mapper.readValue(jsonStr, NameList.class); System.out.println("Created the class"); System.out.print(testObject); } catch (Exception e) { System.out.println("caught the error"); e.printStackTrace(); } } } public class Name { private String field; private String value; //gette