繁体   English   中英

对象数组未按预期运行

[英]array of objects not functioning as expected

我想创建一个具有以下格式的 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"}
 ]
}


代码:

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 


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

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

您正在将 object 添加到另一个 object 中。 这就是你得到它的原因。 你错过了数组

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)

你必须有一个数组变量,然后将每个 json object 添加到数组中

我来宾您需要一个 JSONArray 作为数据。 所以

jsonArray.add(jsonObject);

json.put("数据", jsonArray);

像这样的东西。 我没有测试代码。 不知道是不是叫JSONArray,方法名是不是add。 但是你肯定需要一个 JSONArray 来保存 jsonObject。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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