How to convert list data into json in java

前端 未结 7 1209
天涯浪人
天涯浪人 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: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>(){}.getType();
     List prodList = gson.fromJson(jsonCartList, type);
    
     // print your List
     System.out.println("prodList: " + prodList);
    

提交回复
热议问题