How to convert list data into json in java

前端 未结 7 1182
天涯浪人
天涯浪人 2020-11-30 06:57

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 fun

相关标签:
7条回答
  • 2020-11-30 07:10

    Try these simple steps:

    ObjectMapper mapper = new ObjectMapper();
    String newJsonData = mapper.writeValueAsString(cartList);
    return newJsonData;
    ObjectMapper() is com.fasterxml.jackson.databind.ObjectMapper.ObjectMapper();
    
    0 讨论(0)
  • 2020-11-30 07:11

    Using gson it is much simpler. Use following code snippet:

     // 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);
    

    Converting back from JSON string to your Java object

     // 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);
    
    0 讨论(0)
  • 2020-11-30 07:11

    i wrote my own function to return list of object for populate combo box :

    public static String getJSONList(java.util.List<Object> 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 "";
        }
    

    and call it from anywhere like :

    String toreturn=JSONHelper.getJSONList(list, "com.bean.Contact", "getContactID", "getNumber");
    
    0 讨论(0)
  • 2020-11-30 07:22
    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" } 
        ]
    }
    
    0 讨论(0)
  • 2020-11-30 07:23
    JSONObject responseDetailsJson = new JSONObject();
    JSONArray jsonArray = new JSONArray();
    
    List<String> ls =new  ArrayList<String>();
    
    for(product cj:cities.getList()) {
        ls.add(cj);
        JSONObject formDetailsJson = new JSONObject();
        formDetailsJson.put("id", cj.id);
        formDetailsJson.put("name", cj.name);
        jsonArray.put(formDetailsJson);
    }
    
    responseDetailsJson.put("Cities", jsonArray);
    
    return responseDetailsJson;
    
    0 讨论(0)
  • 2020-11-30 07:27

    Try like below with Gson Library.

    Earlier Conversion List format were:

    [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]]
    

    and here the conversion source begins.

    //** Note I have created the method toString() in Product class.
    
    //Creating and initializing a java.util.List of Product objects
    List<Product> productList = (List<Product>)productRepository.findAll();
    
    //Creating a blank List of Gson library JsonObject
    List<JsonObject> entities = new ArrayList<JsonObject>();
    
    //Simply printing productList size
    System.out.println("Size of productList is : " + productList.size());
    
    //Creating a Iterator for productList
    Iterator<Product> 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);
    

    Converted Json Result is :

    [{"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}]
    

    Hope this would help many guys!

    0 讨论(0)
提交回复
热议问题