如何向JSONArray中添加JSONObject数据

如何向JSONArray中添加JSONObject数据

img


我想变成这样比如第二张图

img

代码如下:

        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再处理

img

你第二张图 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值就行了

img

  • 这有个类似的问题, 你可以参考下: https://ask.csdn.net/questions/267314
  • 这篇博客也不错, 你可以看下JSONObject与JSONArray总结及部分使用
  • 除此之外, 这篇博客: JSONObject和JSONArray区别中的 三、如何从JSONArray中获得JSONObject对象 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • 大家可以把JSONArray当成一般的数组来对待,只是获取的数据内数据的方法不一样

    JSONObject jsonObject = (JSONObject)jsonArray.get(i);
    
    JSONObject jsonObject = jsonArray.getJSONObject(i) ;
    

    两者都可。第一种注意转换