如何在 Java 中将自定义类的 ArrayList 转换为 JsonArray?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18857884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert ArrayList of custom class to JsonArray in Java?
提问by Sean Kilb
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 转换为 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();
采纳答案by Ahsan Shah
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.
哎呀,List
在转换 JSON 树之前使用接口收集值。
回答by cdkrot
List<> is a normal java object, and can be successfully transformed using standard gson object api. List in gson looks like this:
List<> 是一个普通的 java 对象,可以使用标准的 gson 对象 api 成功转换。gson 中的列表如下所示:
"libraries": [
{
//Containing object
},
{
//Containing object
}
],
...
回答by nmanandhan
Use google gson jar, Please see sample code below,
使用 google gson jar,请参阅下面的示例代码,
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);
}
回答by Fadils
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());
回答by Danjoa
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.
很想听听其他人的意见,如果这实际上是低效的,然后是低效的。
回答by Hitesh Sahu
Consider a list of Objects of type Model.class
考虑类型的对象列表 Model.class
ArrayList<Model> listOfObjects = new ArrayList<Model>();
List to JSON
列表到 JSON
String jsonText = new Gson().toJson(listOfObjects);
JSON to LIST
JSON 到列表
Type listType = new TypeToken<List<Model>>() {}.getType();
List<Model> myModelList = new Gson().fromJson(jsonText , listType);
回答by TapanHP
For Anyone who is doing it in Kotlin, you can get it this way,
对于在Kotlin 中执行此操作的任何人,您都可以通过这种方式获得,
val gsonHandler = Gson()
val element: JsonElement = gsonHandler.toJsonTree(yourListOfObjects, object : TypeToken<List<YourModelClass>>() {}.type)