如何使用GSON将List转换为JSON对象? [英] How to convert List to a JSON Object using GSON?
本文介绍了如何使用GSON将List转换为JSON对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个List,我需要使用GSON转换成JSON对象。我的JSON对象中有JSON数组。
public class DataResponse {
private List< ClientResponse>应用;
// getters和setters
public static class ClientResponse {
private double mean;
私人双重偏差;
private int code;
私人字符串包;
private int version;
// getters and setters
}
}
以下是我需要将List转换为JSON数组的JSON代码 -
public void marshal(对象响应){
List< DataResponse.ClientResponse> clientResponse =((DataResponse)响应).getClientResponse();
//现在如何将clientResponse列表转换为使用GSON的JSON数组的JSON对象?
// String jsonObject = ??
}
到目前为止,我在List中只有两个项目 - 所以我需要我的JSON Object like this -
{
apps:[
{
的意思是:1.2,
偏差:1.3
code:100,
pack:hello,
version:1
},
mean:1.5,
deviation:1.1
code:200,
pack:world,
version:2
}
]
}
什么是最好的办法吗? 如果 marshal
方法是一个 DataResponse
,那么这就是你应该序列化的东西。
Gson gson = new Gson();
gson.toJson(response);
这会给你你正在寻找的JSON输出。
I have a List which I need to convert into JSON Object using GSON. My JSON Object has JSON Array in it.
public class DataResponse {
private List<ClientResponse> apps;
// getters and setters
public static class ClientResponse {
private double mean;
private double deviation;
private int code;
private String pack;
private int version;
// getters and setters
}
}
Below is my code in which I need to convert my List to JSON Object which has JSON Array in it -
public void marshal(Object response) {
List<DataResponse.ClientResponse> clientResponse = ((DataResponse) response).getClientResponse();
// now how do I convert clientResponse list to JSON Object which has JSON Array in it using GSON?
// String jsonObject = ??
}
As of now, I only have two items in List - So I need my JSON Object like this -
{
"apps":[
{
"mean":1.2,
"deviation":1.3
"code":100,
"pack":"hello",
"version":1
},
{
"mean":1.5,
"deviation":1.1
"code":200,
"pack":"world",
"version":2
}
]
}
What is the best way to do this?
解决方案
If response
in your marshal
method is a DataResponse
, then that's what you should be serializing.
Gson gson = new Gson();
gson.toJson(response);
That will give you the JSON output you are looking for.
这篇关于如何使用GSON将List转换为JSON对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文