我正在尝试将自定义类的 ArrayList 转换为 JsonArray。下面是我的代码。它执行得很好,但是一些 JsonArray 元素作为 0 出现,即使它们是 ArrayList 中的数字。我试图将它们打印出来。就像 ArrayList 中的 customerOne 年龄是 35 但在 JsonArray 中是 0。有什么问题?
ArrayList<Customer> customerList = CustomerDB.selectAll();
Gson gson = new Gson();
JsonElement element =
gson.toJsonTree(customerList , new TypeToken<List<Customer>>() {}.getType());
JsonArray jsonArray = element.getAsJsonArray();
最佳答案
以下代码应该适用于您的情况。
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();
哎呀,使用 List
接口(interface)在转换 JSON 树之前收集值。
关于java - 如何将自定义类的 ArrayList 转换为 Java 中的 JsonArray?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18857884/