如何在java中将列表数据转换为json [英] How to convert list data into json in java

查看:244
本文介绍了如何在java中将列表数据转换为json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a function which is returning Data as List in java class. Now as per my need, I have to convert it into Json Format.

以下是我的功能代码片段:

Below is my function code snippet:

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类型,它给出了类型不匹配错误...

I tried To convert into json by using this code but it is giving type mismatch error as function is of type 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;

}

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

you can get the data in the following form

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

这篇关于如何在java中将列表数据转换为json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆