How to convert list data into json in java

前端 未结 7 1192
天涯浪人
天涯浪人 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: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 productList = (List)productRepository.findAll();
    
    //Creating a blank List of Gson library JsonObject
    List entities = new ArrayList();
    
    //Simply printing productList size
    System.out.println("Size of productList is : " + productList.size());
    
    //Creating a Iterator for productList
    Iterator 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!

提交回复
热议问题