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 OverflowJava 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)
JSONArray arr = new JSONArray();
HashMap<String, JSONObject> map = new HashMap<String, JSONObject>();
for(int i = 0 ; i < 10 ; i++) {
JSONObject json=new JSONObject();
json.put("id",i);
json.put("firstName","abc"+i);
map.put("json" + i, json);
arr.put(map.get("json" + i));
}
System.println("The json string is " + arr.toString());
OutPut is
The json string is
[
{"id":0,"firstName":"abc0"},
{"id":1,"firstName":"abc1"},
{"id":2,"firstName":"abc2"},
{"id":3,"firstName":"abc3"},
{"id":4,"firstName":"abc4"}
]
List<JSONObject> myJSONObjects = new ArrayList<JSONObject> (productid.size());
for(int i=0; i<productid.size(); i++) {
JSONObject obj = new JSONObject();
obj.put("productid", productid.get(i) );
obj.put("qty", qty.get(i));
obj.put("listprice", listprice.get(i));
myJSONObjects.add(obj);
}
at the end all JSONObjects are in myJSONObjects.
I want to create these JSONObject dynamically as I don't know how many of them are going to be needed while coding.
As you are already having ArrayList, iterate through it and create a new JSONObject in each iteration and put it inside ArrayList<JSONObject>.
For example: JSONObject objJSON;
for(int i=0; i<numberOfItems; i++) {
objJSON = new JSONObject();
objJSON.put("productid", 1);
objJSON.put("qty", 3);
objJSON.put("listprice", 9500);
pdoInformation.put(objJSON);
}
The data will be filled from three ArrayList of productid, qty and listprice
You shouldn't take different ArrayLists because you have to manage each lists as many as you have, instead of that create a single ArrayList of type user defined class. For example, ArrayList<Product> where Product type would contain setter/getter methods.
How to create a json array with multiple objects java spring boot - Stack Overflow
Multiple Objects from one Json file using Jackson
java - Writing of values to multiple JSON objects - Stack Overflow
Best way to create multiple JSON Elements?
I would like to save/load two List objects to a single json file. Can I read/write them in succession somehow or do I have to make a wrapper class first and then read/write the wrapper class?
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"}
]
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!
What you're doing is the correct way to do it. JSON calls always return one object.
The object you got back is an array, so you can extract the elements like this:
var myResponse = makeJSONCall();
// You have received myResponse.length objects, you can bind them
// to variables if you want
var thingOne = myResponse[0];
var thingTwo = myResponse[1];
...
// You can use them from their variable names or straight from the array
thingOne.name = "Joe Bob";
myResponse[3].status = "Tired";
using json lib
List mybeanList = new ArrayList();
mybeanList.add(myBean1);
mybeanList.add(myBean2);
JSONArray jsonArray = JSONArray.fromObject(mybeanList);
You can also use XStream to do this
See Also
- Google gson
I found very good link for JSON: http://code.google.com/p/json-simple/wiki/EncodingExamples#Example_1-1_-_Encode_a_JSON_object
Here's code to add multiple JSONObjects to JSONArray.
JSONArray Obj = new JSONArray();
try {
for(int i = 0; i < 3; i++) {
// 1st object
JSONObject list1 = new JSONObject();
list1.put("val1",i+1);
list1.put("val2",i+2);
list1.put("val3",i+3);
obj.put(list1);
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Toast.makeText(MainActivity.this, ""+obj, Toast.LENGTH_LONG).show();
Once you have put the values into the JSONObject then put the JSONObject into the JSONArray staright after.
Something like this maybe:
jsonObj.put("value1", 1);
jsonObj.put("value2", 900);
jsonObj.put("value3", 1368349);
jsonArray.put(jsonObj);
Then create new JSONObject, put the other values into it and add it to the JSONArray:
jsonObj.put("value1", 2);
jsonObj.put("value2", 1900);
jsonObj.put("value3", 136856);
jsonArray.put(jsonObj);
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.
You should write both objects, as below:
write.write(vjo.toString());
write.newLine();
write.write(conb.toString());
write.newline();
write.flush();
write.close();
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.
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"}}
}
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();
}
}
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();
}