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 ArrayList. I have tried to print them out. Like customerOne age in the ArrayList is 35 but it is 0 in the JsonArray. What could be wrong?
ArrayList<Customer> customerList = CustomerDB.selectAll(); Gson gson = new Gson(); JsonElement element = gson.toJsonTree(customerList , new TypeToken<List<Customer>>() {}.getType()); JsonArray jsonArray = element.getAsJsonArray();
We can convert a list to the JSON array using the JSONArray. toJSONString() method and it is a static method of JSONArray, it will convert a list to JSON text and the result is a JSON array.
Object[] toArray() method in java This way of converting an ArrayList to Array in Java uses the toArray() method from the java List interface and returns an array of type Object. It will convert the list to an array without disturbing the sequence of the elements.
There are four ways to convert ArrayList to HashSet :Using constructor. Using add() method by iterating over each element and adding it into the HashSet. Using addAll() method that adds all the elements in one go into the HashSet. Using stream.
We can also add a JSONArray to JSONObject. We need to add a few items to an ArrayList first and pass this list to the put() method of JSONArray class and finally add this array to JSONObject using the put() method.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With