title: How to convert list data into json in java
body: <p>I have a function which is returning Data as <code>List</code> in java class. Now as per my need, I have to convert it into <code>Json</code> Format.</p>
  
  <p>Below is my function code snippet:</p>
  
  <pre><code>public static List&lt;Product&gt; getCartList() {
      List&lt;Product&gt; cartList = new Vector&lt;Product&gt;(cartMap.keySet().size());
      for(Product p : cartMap.keySet()) {
          cartList.add(p);
      }
      return cartList;
  }
  </code></pre>
  
  <p>I tried To convert into <code>json</code> by using this code but it is giving type mismatch error as function is of type List...</p>
  
  <pre><code>public static List&lt;Product&gt; getCartList() {
      List&lt;Product&gt; cartList = new Vector&lt;Product&gt;(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;
  
          }
  </code></pre>
  
  <p>Please help me resolve this.</p>