How to convert ArrayList of custom class to JsonArray in Java?

前端 未结 7 2236
一个人的身影
一个人的身影 2021-02-03 22:18

I am trying to convert ArrayList of custom class to JsonArray. Below is my code. It executes fine but some JsonArray elements come as zeros even though they are numbers in the A

7条回答
  •  南笙
    南笙 (楼主)
    2021-02-03 22:43

    Below code should work for your case.

    List customerList = CustomerDB.selectAll();
    
    Gson gson = new Gson();
    JsonElement element = gson.toJsonTree(customerList, new TypeToken>() {}.getType());
    
    if (! element.isJsonArray() ) {
    // fail appropriately
        throw new SomeException();
    }
    
    JsonArray jsonArray = element.getAsJsonArray();
    

    Heck, use List interface to collect values before converting it JSON Tree.

提交回复
热议问题