I have a List which I need to convert into JSON Object using GSON. My JSON Object has JSON Array in it.

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

What is the best way to do this?

推荐答案

If response in your marshal method is a DataResponse, then that's what you should be serializing.

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

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

Json相关问答推荐

如何在使用GO时检测JSON中不需要的字段?

从Json响应中为需要每个值的Post请求提取多个值

Vega Lite中的图例对齐

如何在Android中解析带有动态键和可变对象名称的改装JSON响应?

当列为空时从 SQL 获取 JSON

在 VS Code 中将一个正则表达式替换为另一个正则表达式

将不带正文的 CURL POST 转换为 RESTRequest Delphi 代码 / 为 Dropbox API /get_current_account 端点编写 Delphi 代码

JOLT 转换仅过滤一个字段

JOLT JSON 将值从一对多转换为一对一

JOLT 在 struct 体中间添加一个 JSON 字段

Serde JSON 反序列化枚举

使用 jq 获取特定键的所有父键

如何使用 React 从 NASA IMAGES API 中解构所需信息

SwiftUI:如何使用 0 索引数组键为 JSON 添加类型

杰克逊 2.0 和 Spring 3.1

使用 @ResponseBody 自定义 HttpMessageConverter 来做 Json 事情

如何在 Perl 中将简单的哈希转换为 json?

使用 Node.js 对 JSON 中的字符串大小有限制吗?

我可以使用空字符串作为对象标识符吗?

JSON.stringify 向我的 Json 对象添加额外的 \ 和 "" 的问题