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 A
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());
Use google gson jar, Please see sample code below,
public class Metric {
private int id;
...
setter for id
....
getter for id
}
Metric metric = new Metric();
metric.setId(1);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.serializeNulls();
Gson gson = gsonBuilder.create();
System.out.println(gson.toJson(metric));
StringBuffer jsonBuffer = new StringBuffer("{ \"rows\": [");
List<Metric> metrices = new ArrayList<Metric>();
// assume you have more elements in above arraylist
boolean first = true;
for (Metric metric : metrices) {
if (first)
first = false;
else
jsonBuffer.append(",");
jsonBuffer.append(getJsonFromMetric(metric));
}
jsonBuffer.append("]}");
private String getJsonFromMetric(Metric metric) {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.serializeNulls();
Gson gson = gsonBuilder.create();
return gson.toJson(metric);
}
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.
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.
For Anyone who is doing it in Kotlin, you can get it this way,
val gsonHandler = Gson()
val element: JsonElement = gsonHandler.toJsonTree(yourListOfObjects, object : TypeToken<List<YourModelClass>>() {}.type)
List<> is a normal java object, and can be successfully transformed using standard gson object api. List in gson looks like this:
"libraries": [
{
//Containing object
},
{
//Containing object
}
],
...