如何向JSONArray中添加JSONObject数据
代码如下:
ArrayList<CustomerTank> customerTanks = tankMapper.selectCustomerTank(user.getId());
JSONArray array= JSONArray.parseArray(JSON.toJSONString(customerTanks));
JSONObject json_data = new JSONObject();
// data 内容为json数组
JSONArray jsonArray = new JSONArray();
JSONObject json = new JSONObject();;
json_data.put("records",jsonArray);
for (int i=1;i<=1;i++){
json.put("fight_power","120");
json.put("expected_revenue","100~120");
//"fight_power" 为data数组的元素
jsonArray.add(json);
}
array.add(json_data);
return ResultVM.ok("获取用户坦克列表成功",array);
遍历jsonArray再处理
你第二张图 records外面 少了大括号都不是标准的json格式。
如果你的jsonArray只有一条记录的话,你从array中获取到这个然后 put 添加新的属性就行。
就像这种
{
"code": 200,
"msg": "获取用户坦克列表成功",
"data": {
"records": [
{
"expected_revenue": "100~120",
"fight_power": "120",
"shootSpeed":2,
"fatigue":0,
"moveSpeed":2,
"level":1,
"hp":2,
"name":"坦克2",
"tankId":2,
"id":25,
"power":2,
"quality":0,
"tankColorId":1
}
]
}
}
获取你的 data这一级然后往里边put值就行了
大家可以把JSONArray当成一般的数组来对待,只是获取的数据内数据的方法不一样
JSONObject jsonObject = (JSONObject)jsonArray.get(i);
JSONObject jsonObject = jsonArray.getJSONObject(i) ;
两者都可。第一种注意转换