Java JSON数组中出现{"$ref":"$[0]"}

出现这个问题原因主要是同一对象重复引用,并重复赋值

一般在for循环中很可能会出现

有问题的代码类似这样重复给JSONObject对象赋值

JSONObject jsonObject1 = new JSONObject();//这里的JSONObject在循环体外声明
        for (int i=0;i<list.size();i++){
            order = list.get(i);
            jsonObject1.put("orderid",order.getOrderId());
            SimpleDateFormat date1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            jsonObject1.put("create_time",date1.format(order.getCreateTime()));
            jsonObject1.put("price",order.getOrderPrice());
            jsonObject1.put("count",order.getCount());
            //System.out.println(jsonObject1);
            List<OrderDetails> list1 = orderDetailsService.selectByOrderId(order.getOrderId());
            //System.out.println("订单详情表中的订单id为"+order.getOrderId()+list1);
            JSONArray jsonArray1 = new JSONArray();
            }

这里的JSONObject在循环体外声明,所以每执行一次循环,JSONObject对象会被重复引用
,一般用过其他语言的人,可能会觉得后面JSONObject的重新赋值不会影响之前已经赋给JSONArray数组的值。
但我将JSONArray的内容打印出来发现了{" r e f &quot; : &quot; ref&quot;:&quot; ref":"[0]"}

第0个jsonarray[{"count":25,"create_time":"2019-03-25 20:07:51","goods_url":["/image/1.jpg","/image/7.jpg"],
"orderid":1,"price":546}]
第1个jsonarray[{"count":6,"create_time":"2019-03-25 17:41:20","goods_url":["/image/3.jpg","/image/2.jpg"],
"orderid":2,"price":213},{"$ref":"$[0]"}]//这里
[{"count":6,"create_time":"2019-03-25 17:41:20","goods_url":["/image/3.jpg","/image/2.jpg"],
"orderid":2,"price":213},{"$ref":"$[0]"}]//这里

如图,这样打印出来数组里面存的JSONObject对象的内容是一样的

解决方法就是将循环体中要用JSONObject对象在循环体内声明,这样每次循环引用的JSONObject对象就都是新的

  for (int i=0;i<list.size();i++){
  		JSONObject jsonObject1 = new JSONObject();//这里的JSONObject在循环体里面声明
      order = list.get(i);
      jsonObject1.put("orderid",order.getOrderId());
      SimpleDateFormat date1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      jsonObject1.put("create_time",date1.format(order.getCreateTime()));
      jsonObject1.put("price",order.getOrderPrice());
      jsonObject1.put("count",order.getCount());
      //System.out.println(jsonObject1);
      List<OrderDetails> list1 = orderDetailsService.selectByOrderId(order.getOrderId());
      //System.out.println("订单详情表中的订单id为"+order.getOrderId()+list1);
      JSONArray jsonArray1 = new JSONArray();
      }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值