0

Here is my code for storing multiple JSON objects into an array and then I want to convert the array into a single string.

String message =null;
JSONObject json = new JSONObject();
json.put("name","student");
json.put("name", "Atal");
json.put("name","Rachit");


JSONArray array = new JSONArray();
for(int i= 0; i<= array.length(); i++) {    
    array.put(json);
    message = array.toJSONString();
}

I want to get the output as a string and store it in a message variable.

Pavel Smirnov
  • 4,611
  • 3
  • 18
  • 28
  • 2
    You are replacing `name` each time you are calling `json.put()`. could you post a sample output that you want to print? – Kapil Dec 17 '19 at 07:05
  • Thanks it worked. i was actually replacing name everytime i was calling json.put() . – Atal Dangwal Dec 19 '19 at 07:14

2 Answers2

0
String message =null;
JSONObject json = new JSONObject();
json.put("name","student");
json.put("name", "Atal");
json.put("name","Rachit");


JSONArray array = new JSONArray();
//for(int i= 0; i<= array.length(); i++) {    
//    array.put(json);
//    message = array.toJSONString();
//}
array.put(json); //There is a JSON,just put it into the array
message = array.toJSONString();

  • With this, it will only store the last json.put("name","Rachit") int the array but i want to store all the three json.put statements in the array. – Atal Dangwal Dec 19 '19 at 07:03
0

I was replacing "name" every time I was calling json.put()

String message =null;
JSONObject json = new JSONObject();
json.put("name","Atal");
json.put("class", "10");
json.put("Roll","1035");


JSONArray array = new JSONArray();

array.put(json);
message = array.toJSONString();