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

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.


As an additional answer, it can also be made shorter.

List<Customer> customerList = CustomerDB.selectAll();JsonArray result = (JsonArray) new Gson().toJsonTree(customerList,            new TypeToken<List<Customer>>() {            }.getType());


Don't know how well this solution performs compared to the other answers but this is another way of doing it, which is quite clean and should be enough for most cases.

ArrayList<Customer> customerList = CustomerDB.selectAll();Gson gson = new Gson();String data = gson.toJson(customerList);JsonArray jsonArray = new JsonParser().parse(data).getAsJsonArray();

Would love to hear from someone else though if, and then how, inefficient this actually is.