出现这个问题原因主要是同一对象重复引用,并重复赋值
一般在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
"
:
"
ref":"
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();
}