如何在 Java 中将自定义类的 ArrayList 转换为 JsonArray? [英] How to convert ArrayList of custom class to JsonArray in Java?

查看:41
本文介绍了如何在 Java 中将自定义类的 ArrayList 转换为 JsonArray?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将自定义类的 ArrayList 转换为 JsonArray.下面是我的代码.它执行得很好,但即使它们是 ArrayList 中的数字,一些 JsonArray 元素也会为零.我试过把它们打印出来.就像 ArrayList 中的 customerOne 年龄是 35,但它在 JsonArray 中是 0.可能有什么问题?

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();

推荐答案

以下代码应该适用于您的情况.

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();

哎呀,使用 List 接口在将其转换为 JSON 树之前收集值.

Heck, use List interface to collect values before converting it JSON Tree.

这篇关于如何在 Java 中将自定义类的 ArrayList 转换为 JsonArray?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆