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

vik*_*kas 16 java json list

我有一个函数,它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)

请帮我解决这个问题.

anu*_*ava 29

使用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);
Run Code Online (Sandbox Code Playgroud)

从JSON字符串转换回Java对象

 // Converts JSON string into a List of Product object
 Type type = new TypeToken<List<Product>>(){}.getType();
 List<Product> prodList = gson.fromJson(jsonCartList, type);

 // print your List<Product>
 System.out.println("prodList: " + prodList);
Run Code Online (Sandbox Code Playgroud)


PSR*_*PSR 17

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;

}
Run Code Online (Sandbox Code Playgroud)

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

{
    "forms": [
        { "id": "1", "name": "name1" },
        { "id": "2", "name": "name2" } 
    ]
}
Run Code Online (Sandbox Code Playgroud)

  • 您需要将相关的jar文件添加到包含org.json.simple.JSONArray,org.json.simple.JSONObject类的类路径中. (3认同)

小智 5

试试这些简单的步骤:

ObjectMapper mapper = new ObjectMapper();
String newJsonData = mapper.writeValueAsString(cartList);
return newJsonData;
ObjectMapper() is com.fasterxml.jackson.databind.ObjectMapper.ObjectMapper();
Run Code Online (Sandbox Code Playgroud)