我有一个函数返回List
java类中的数据。现在,根据我的需要,我必须将其转换为Json
Format。
以下是我的功能代码段:
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;
}
请帮我解决这个问题。
public static List<Product> getCartList() {
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = new JSONArray();
List<Product> cartList = new Vector<Product>(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;
}
您可以通过以下形式获取数据
{
"forms": [
{ "id": "1", "name": "name1" },
{ "id": "2", "name": "name2" }
]
}
在我的Spring Boot项目中,我有两个类(实体和模型) 在模型中有一个列表 :
问题内容: 如果我有一个,如何通过使用Java 8的功能将其转换为以相同的迭代顺序包含所有对象的? 问题答案: 你可以用于将内部列表(将它们转换为Streams之后)展平为单个Stream,然后将结果收集到列表中:
问题内容: 我有以下格式的行: 现在,我要在文件中写入以下内容: 基本上将上面转换成jsonarray? Python中是否有内置方法,库或函数可将数组“转储”到json数组中? 另请注意,我不希望在文件中序列化“ L”。 问题答案: 使用该模块生成JSON输出: 这会将JSON结果直接写入文件(如果文件已经存在,则替换任何先前的内容)。 如果您需要Python本身中的JSON结果字符串,请使用(
问题内容: 在Java中,如何获取作为a返回的值? 问题答案:
问题内容: 最近我谈话有什么将要转换的最佳方式是同事,以在Java中,如果有这样做的任何特殊利益。 我想知道最佳转换方法,如果有人可以指导我,我将不胜感激。 这是个好方法吗? 问题答案: 当然,假设每个Item都有一个返回正确类型的键的方法。
问题内容: 如何在Java中将数组转换为列表? 我使用了,但是行为(和签名)从Java SE 1.4.2(现在已存档的文档)以某种方式改变为8,我在网络上发现的大多数代码片段都使用1.4.2行为。 例如: 在1.4.2上返回包含元素1,2,3的列表 在1.5.0+上返回包含垃圾邮件数组的列表 在许多情况下,它应该很容易检测到,但是有时它可能会被忽略而不会引起注意: 问题答案: 在你的示例中,这是因