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

问题描述 投票:0回答:5

我有一个列表,我需要使用 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
      }
   ]
}

最好的方法是什么?

java arrays json gson
5个回答
89
投票

有一个来自 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字符串,反之亦然。


44
投票

如果

response
方法中的
marshal
DataResponse
,那么这就是您应该序列化的内容。

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

这将为您提供所需的 JSON 输出。


15
投票

假设您还想获取格式为 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);

0
投票

确保首先将您的集合转换为数组:

Gson().toJson(objectsList.toTypedArray(), Array<CustomObject>::class.java)

-3
投票

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

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

优点:

  • 我们这里没有使用反射。 :)
© www.soinside.com 2019 - 2024. All rights reserved.