我有一个列表,我需要使用 GSON 将其转换为 JSON 对象。我的 JSON 对象中有 JSON 数组。
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
}
}
下面是我的代码,我需要在其中将我的列表转换为其中包含 JSON 数组的 JSON 对象 -
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 = ??
}
截至目前,列表中只有两项 - 所以我需要这样的 JSON 对象 -
{
"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
}
]
}
做这个的最好方式是什么?
原文由 AKIWEB 发布,翻译遵循 CC BY-SA 4.0 许可协议
如果
response
在您的marshal
方法中是DataResponse
,那么这就是您应该序列化的内容。这将为您提供所需的 JSON 输出。