如何使用GSON将List转换为JSON对象?

我有一个List,我需要使用GSON转换为JSON对象。 我的JSON对象中包含JSON数组。

public class DataResponse { private List 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 } } 

下面是我的代码,我需要将我的List转换为JSON对象,其中包含JSON数组 –

 public void marshal(Object response) { List 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 } ] } 

做这个的最好方式是什么?

如果您的marshal方法中的responseDataResponse ,那么您应该序列化。

 Gson gson = new Gson(); gson.toJson(response); 

这将为您提供您正在寻找的JSON输出。

google gson 文档中有一个关于如何将列表实际转换为json字符串的示例:

 Type listType = new TypeToken>() {}.getType(); List target = new LinkedList(); target.add("blah"); Gson gson = new Gson(); String json = gson.toJson(target, listType); List target2 = gson.fromJson(json, listType); 

您需要在toJson方法中设置列表类型并传递list对象以将其转换为json字符串,反之亦然。

假设你也希望以格式获得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 } ] } 

代替

 {"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}]} 

你可以使用漂亮的印刷 。 这样做使用

 Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(dataResponse); 

我们还可以使用另一种解决方法,首先创建一个myObject数组,然后将它们转换为列表。

 final Optional> sortInput = Optional.ofNullable(jsonArgument) .map(jsonArgument -> GSON.toJson(jsonArgument, ArrayList.class)) .map(gson -> GSON.fromJson(gson, MyObject[].class)) .map(myObjectArray -> Arrays.asList(myObjectArray)); 

作用:

  • 我们这里没有使用reflection。 🙂