Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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(); 
like image 697
Sean Kilb Avatar asked Sep 17 '13 19:09

Sean Kilb


People also ask

How can we convert a list to the JSON array in Java?

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.

Can you convert an ArrayList to an array in Java?

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.

Can we convert ArrayList set?

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.

Can we convert JSONArray to JSONObject?

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.


2 Answers

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.

like image 183
Ahsan Shah Avatar answered Sep 21 '22 08:09

Ahsan Shah


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()); 
like image 35
Fadils Avatar answered Sep 22 '22 08:09

Fadils