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.
Consider a list of Objects of type Model.class
ArrayList<Model> listOfObjects = new ArrayList<Model>();
List to JSON
String jsonText = new Gson().toJson(listOfObjects);
JSON to LIST
Type listType = new TypeToken<List<Model>>() {}.getType();
List<Model> myModelList = new Gson().fromJson(jsonText , listType);
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.
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());