Java 对象数组未按预期运行

Java 对象数组未按预期运行,java,android,arrays,json,Java,Android,Arrays,Json,我想用以下格式创建一个json, 如何将多个对象添加到单个数组中。 { Data: [ {"dataType":"com.google.weight", "startDate":"2021-04-1308:00", "endDate":"2021-04-13", "Weight":"65"}, {"

我想用以下格式创建一个json,
如何将多个对象添加到单个数组中。

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


代码:

使用上面的代码,我得到以下结果。这将替换所有其他值并仅打印一个对象。我想要一个对象数组。任何帮助都将是伟大的

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

您必须有一个数组变量,然后将每个json对象添加到数组中

I如果您需要一个JSONArray作为数据。
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)
所以

put(“数据”,jsonArray)


像这样的。我没有测试代码。我不确定它是否被称为JSONArray,方法名是否为add。但是您肯定需要一个JSONArray来保存jsonObject。

您正在将一个对象添加到另一个对象中。这就是为什么你会这样。你错过了阵列

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)
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)