我有一个函数,它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)
请帮我解决这个问题.
我从数据库收到以下列表,我想将其转换为 JSON:
Employee e1=new Employee(101,"Ha","De","Acr");
Employee e2=new Employee(102,"D ","Forouzan","Mc");
Employee e3=new Employee(102,"Op","Ga","Wi");
Employee e4=new Employee(101,"YUI","HI","EX");
Run Code Online (Sandbox Code Playgroud)
我想改变它只是它遍历上面收到的列表,对于重复的键 (101, 102),它使用数组创建一个 jsoobject;
ex: 101 : {["Ha","De","Acr"],["YUI","HI","EX"]}
Run Code Online (Sandbox Code Playgroud) 我想下面的JSON,在那里List<form>将有一个名单form_id,form_name我怎么可以把这个使用的JSONObject,我没有得到正确的JSON输出.请帮我解决一下这个.JSON:
{
"forms": [
{ "form_id": "1", "form_name": "test1" },
{ "form_id": "2", "form_name": "test2" }
]
}
Run Code Online (Sandbox Code Playgroud)
以上是我需要它的json结构列表.其中id,name是来自表单对象的列表
public static JSONObject getJsonFromMyFormObject(List<Form> form) {
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = null;
System.out.println(form.size());
for (int i = 0; i < form.size(); i++) {
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("form_id", form.get(i).getId());
formDetailsJson.put("form_name", form.get(i).getName());
jsonArray = new JSONArray();
jsonArray.add(formDetailsJson);
}
responseDetailsJson.put("form", jsonArray);
return responseDetailsJson;
}
Run Code Online (Sandbox Code Playgroud)
这里面临的问题是没有将输出作为列表