How to convert list data into json in java

前端 未结 7 1184
天涯浪人
天涯浪人 2020-11-30 06:57

I have a function which is returning Data as List in java class. Now as per my need, I have to convert it into Json Format.

Below is my fun

7条回答
  •  离开以前
    2020-11-30 07:22

    public static List getCartList() {
    
        JSONObject responseDetailsJson = new JSONObject();
        JSONArray jsonArray = new JSONArray();
    
        List cartList = new Vector(cartMap.keySet().size());
        for(Product p : cartMap.keySet()) {
            cartList.add(p);
            JSONObject formDetailsJson = new JSONObject();
            formDetailsJson.put("id", "1");
            formDetailsJson.put("name", "name1");
           jsonArray.add(formDetailsJson);
        }
        responseDetailsJson.put("forms", jsonArray);//Here you can see the data in json format
    
        return cartList;
    
    }
    

    you can get the data in the following form

    {
        "forms": [
            { "id": "1", "name": "name1" },
            { "id": "2", "name": "name2" } 
        ]
    }
    

提交回复
热议问题