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

AKI*_*WEB 24 java arrays json gson

我有一个List,我需要使用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
    }
}
Run Code Online (Sandbox Code Playgroud)

下面是我的代码,我需要将我的List转换为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 = ??
}
Run Code Online (Sandbox Code Playgroud)

截至目前,我在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
      }
   ]
}
Run Code Online (Sandbox Code Playgroud)

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

Rod*_*uin 57

google gson 文档中有一个关于如何将列表实际转换为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);
Run Code Online (Sandbox Code Playgroud)

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

  • 这实际上是我唯一有效的答案. (10认同)

Sot*_*lis 31

如果response你的marshal方法是a DataResponse,那就是你应该序列化的.

Gson gson = new Gson();
gson.toJson(response);
Run Code Online (Sandbox Code Playgroud)

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


Psh*_*emo 7

假设您还想获取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
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

代替

{"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}]}
Run Code Online (Sandbox Code Playgroud)

您可以使用漂亮的打印。为此使用

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(dataResponse);
Run Code Online (Sandbox Code Playgroud)

  • 漂亮的打印很棒 - 生成的 JSON 可读:-) (3认同)