简体   繁体   中英

array of objects not functioning as expected

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"}
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM