如何将对象列表转换为jsonObject?


  我将Pojo类的列表转换为jsonObject。我将整个列表转换为jsonArray,但是如何在数组范围之外添加其他字段?


            List<Order> items = new ArrayList<>();
            if (checkOutList != null) {
                for (Category.Items i1 : checkOutList) {
                    Order order = new Order();
                    order.setC_id(i1.getCid());
                    order.setItem_id(i1.getItem_id());
                    order.setQuantity(i1.getCount());
                    items.add(order);
                }
                Order order = new Order();
                order.setOd_total_cost(cardValue.getText().toString().trim());
                order.setR_id(checkOutList.get(0).getRid());
                order.setU_id("5");
                items.add(order);

                Gson gson = new GsonBuilder().create();
                JsonArray myCustomArray = gson.toJsonTree(items).getAsJsonArray();
                Log.e("order", myCustomArray.toString());
            }


上面的代码给了我输出:

[{"c_id":"3","item_id":"18","quantity":"5"},{"od_total_cost":"Card Value: $30.14","r_id":"1","u_id":"5"}]


我想要的输出

{"items":[{"quantity":"25","c_id":"70","item_id":"10"}],"r_id":"5","u_id":"70","od_total_cost":"20000"}


更新

JsonElement jsonObject=gson.toJsonTree(order);
Log.e("order", myCustomArray.toString()+jsonObject.toString());



  上面添加的一行给了我下面的输出,现在如何添加arrayname:items?并将整个输出添加为json对象


[{"c_id":"3","item_id":"18","quantity":"5"},{"c_id":"3","item_id":"17","quantity":"2"},{"c_id":"2","item_id":"91","quantity":"2"},{"c_id":"2","item_id":"9","quantity":"1"}]{"od_total_cost":"Card Value: $20.16","r_id":"1","u_id":"5"}

最佳答案

我认为其他方式也有效,但是我也可以使用POJO。

    class WholeObject{
        List<Order> items;
        String r_id;
        String u_id;
        String od_total_cost;

        //---getters and setters---

    }

    WholeObject wo = new WholeObject();
    wo.setR_id("5");
    wo.setU_id("70");
    wo.setOd_total_cost("20000");
    wo.setItems(yourOrders);

    Log.e("order",  new Gson().toJson( wo ) );

10-06 02:35