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

Below code should work for your case.

List<Customer> customerList = CustomerDB.selectAll();

Gson gson = new Gson();
JsonElement element = gson.toJsonTree(customerList, new TypeToken<List<Customer>>() {}.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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)