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

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

以下是我的function代码片段:

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

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

 public static List getCartList() { List cartList = new Vector(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 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; } 

您可以使用以下格式获取数据

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

使用gson它更简单。 使用以下代码段:

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

从JSON字符串转换回Java对象

  // Converts JSON string into a List of Product object Type type = new TypeToken>(){}.getType(); List prodList = gson.fromJson(jsonCartList, type); // print your List System.out.println("prodList: " + prodList); 

我编写了自己的函数来返回populatecombobox的对象列表:

 public static String getJSONList(java.util.List list,String kelas,String name, String label) { try { Object[] args={}; Class cl = Class.forName(kelas); Method getName = cl.getMethod(name, null); Method getLabel = cl.getMethod(label, null); String json="["; for (int i = 0; i < list.size(); i++) { Object o = list.get(i); if(i>0){ json+=","; } json+="{\"label\":\""+getLabel.invoke(o,args)+"\",\"name\":\""+getName.invoke(o,args)+"\"}"; //System.out.println("Object = " + i+" -> "+o.getNumber()); } json+="]"; return json; } catch (ClassNotFoundException ex) { Logger.getLogger(JSONHelper.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { System.out.println("Error in get JSON List"); ex.printStackTrace(); } return ""; } 

并从以下任何地方调用它:

 String toreturn=JSONHelper.getJSONList(list, "com.bean.Contact", "getContactID", "getNumber"); 

使用Gson Library尝试下面的内容。

早期转换列表格式为:

 [Product [Id=1, City=Bengalore, Category=TV, Brand=Samsung, Name=Samsung LED, Type=LED, Size=32 inches, Price=33500.5, Stock=17.0], Product [Id=2, City=Bengalore, Category=TV, Brand=Samsung, Name=Samsung LED, Type=LED, Size=42 inches, Price=41850.0, Stock=9.0]] 

这里转换源开始了。

 //** Note I have created the method toString() in Product class. //Creating and initializing a java.util.List of Product objects List productList = (List)productRepository.findAll(); //Creating a blank List of Gson library JsonObject List entities = new ArrayList(); //Simply printing productList size System.out.println("Size of productList is : " + productList.size()); //Creating a Iterator for productList Iterator iterator = productList.iterator(); //Run while loop till Product Object exists. while(iterator.hasNext()){ //Creating a fresh Gson Object Gson gs = new Gson(); //Converting our Product Object to JsonElement //Object by passing the Product Object String value (iterator.next()) JsonElement element = gs.fromJson (gs.toJson(iterator.next()), JsonElement.class); //Creating JsonObject from JsonElement JsonObject jsonObject = element.getAsJsonObject(); //Collecting the JsonObject to List entities.add(jsonObject); } //Do what you want to do with Array of JsonObject System.out.println(entities); 

转换的Json结果是:

 [{"Id":1,"City":"Bengalore","Category":"TV","Brand":"Samsung","Name":"Samsung LED","Type":"LED","Size":"32 inches","Price":33500.5,"Stock":17.0}, {"Id":2,"City":"Bengalore","Category":"TV","Brand":"Samsung","Name":"Samsung LED","Type":"LED","Size":"42 inches","Price":41850.0,"Stock":9.0}] 

希望这会对很多人有所帮助!

使用GSON库将列表对象转换为json

 // import import com.google.gson.Gson; // Create gson object Gson gSon = new Gson(); // Create list of object List cartList = new ArrayList(); Employee emp1=new Employee(); emp1.setEmployeeId(1); emp1.setEmployeeName("Martin"); emp1.setEmployeeAge(24); employeeList.add(emp1); String jsonCartList = gSon.toJson(cartList); 

示例: 将list转换为json