我有一个函数返回Java类中的List
数据。现在根据我的需求,我需要将它转换成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;
}
我尝试使用这段代码将其转换为 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;
}
请帮我解决这个问题。