小编vik*_*kas的帖子

如何在java中将列表数据转换为json

我有一个函数,它List在java类中返回Data .现在根据我的需要,我必须将其转换为Json格式.

以下是我的功能代码片段:

public static List<Product> getCartList() {
    List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
    for(Product p : cartMap.keySet()) {
        cartList.add(p);
    }
    return cartList;
}
Run Code Online (Sandbox Code Playgroud)

我试图json通过使用此代码转换为但它给出类型不匹配错误,因为函数是List类型...

public static List<Product> getCartList() {
    List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
    for(Product p : cartMap.keySet()) {
        cartList.add(p);
    }

    Gson gson = new Gson();
     // convert your list to json
     String jsonCartList = gson.toJson(cartList);
     // print your generated json
     System.out.println("jsonCartList: " + jsonCartList);

     return jsonCartList;

        }
Run Code Online (Sandbox Code Playgroud)

请帮我解决这个问题.

java json list

16
推荐指数
3
解决办法
14万
查看次数

标签 统计

java ×1

json ×1

list ×1