array of objects not functioning as expected

Viewed 41

I want to create a json with the below format,
How can i add many objects into a single array.

{
Data: [
   {"dataType":"com.google.weight",
   "startDate":"2021-04-1308:00",
   "endDate":"2021-04-13",
   "Weight":"65"},

   {"dataType":"com.google.weight",
   "startDate":"2021-04-1308:00",
   "endDate":"2021-04-13",
   "Weight":"85"},

   {"dataType":"com.google.weight",
   "startDate":"2021-04-1308:00",
   "endDate":"2021-04-13",
   "Weight":"95"}
 ]
}


Code:

JSONObject jsonObject = new JSONObject();
JSONObject json  = new JSONObject();

jsonObject.put("dataType", dataSet.getDataType().getName().toString());
jsonObject.put("startDate", dateFormat.format(dp.getStartTime().toString());
jsonObject.put("endDate", dateFormat.format(dp.getEndTime().toString());
jsonObject.put("Weight", dp.getValue(field).toString());

json.put("Data", jsonObject)         //this is wrong i guess. it replaces all the old values 


Using the above code i get the below result. This is replacing all the other values and printing only one object. I want an array of objects. any help would be great!!!

{
Data: 
   {"dataType":"com.google.weight",
   "startDate":"2021-04-1308:00",
   "endDate":"2021-04-13",
   "Weight":"95"}
}
3 Answers

you are adding an object into another object. that's why you got that. You missed the array

JSONObject jsonObject = new JSONObject();
JSONObject json  = new JSONObject();

jsonObject.put("dataType", dataSet.getDataType().getName().toString());
jsonObject.put("startDate", dateFormat.format(dp.getStartTime().toString());
jsonObject.put("endDate", dateFormat.format(dp.getEndTime().toString());
jsonObject.put("Weight", dp.getValue(field).toString());

// you missed this
JSONArray jsonArray = new JSONArray();
jsonArray.put(jsonObject);

// now you put an array into an object
json.put("Data", jsonArray)

you must have an array var, then add each of the json object into the array

I guest you need a JSONArray to be put as Data. So

jsonArray.add(jsonObject);

json.put("Data", jsonArray);

Something like this. I did not test the code. I am not sure whether it is called JSONArray, whether the method name is add. But you definitely need an JSONArray to hold the jsonObject.

Related