我有一个需要使用 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 = ??
}
到目前为止,我在 List 中只有两个项目 - 所以我需要这样的 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
}
]
}
最好的方法是什么?
最佳答案
有一个来自 google gson documentation 的示例关于如何将列表实际转换为 json 字符串:
Type listType = new TypeToken<List<String>>() {}.getType();
List<String> target = new LinkedList<String>();
target.add("blah");
Gson gson = new Gson();
String json = gson.toJson(target, listType);
List<String> target2 = gson.fromJson(json, listType);
您需要在toJson
方法中设置列表的类型,并传递列表对象将其转换为json字符串,反之亦然。
关于java - 如何使用 GSON 将 List 转换为 JSON 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27893342/