简体   繁体   English

如何将正确的 JSON 从服务器端 java 返回到 DataTables?

[英]How to return the correct JSON from the server-side java to DataTables?

How do I concatenate two arrays and then return the result as JSON to DataTables?如何连接两个数组,然后将结果作为 JSON 返回到 DataTables?

I am converting a working DataTables to include server-side processing and am stuck on returning the correct array from the java server-side.我正在转换一个工作数据表以包含服务器端处理,并坚持从 java 服务器端返回正确的数组。 Currently the array returned is:目前返回的数组是:

List<YthMmbrSectDtls> ymList;

Example data is:示例数据是:

[{"youthMemberID":"MTQ5","surname":"Tendon","firstName":"Achilles"}]

With the DataTables server-side I need to include extra information at the start of the returned JSON such as:对于 DataTables 服务器端,我需要在返回的 JSON 的开头包含额外的信息,例如:

{"draw":9, "recordsTotal:57", "recordsFiltered:57"[...]}

So that I return:所以我回来了:

{"draw":9, "recordsTotal:57", "recordsFiltered:57","data":[{"youthMemberID":"MTQ5","surname":"Tendon","firstName":"Achilles"}]}

At least that is my understanding from reading the manuals and watching the videos.至少这是我阅读手册和观看视频的理解。

My current code is:我目前的代码是:

List<YthMmbrSectDtls> ymList;
String[] dtInfo = {"draw", "recordsTotal", "recordsFiltered"};

ymList = MySQLConnection.getYouthMmbrAllDtls(archived);
        
//Test to be replaced by database call, as per above
dtInfo[0] = "9";
dtInfo[1] = "57";
dtInfo[2] = "57";

if (ymList == null || ymList.isEmpty()) {
    response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No members.");
} else {
    System.out.println("ymList: " + ymList);
    String json = new Gson().toJson(ymList);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

There are multiple different ways this can be solved:有多种不同的方法可以解决这个问题:

Modify JsonElement tree修改 JsonElement 树

You can first use Gson.toJsonTree(Object) to convert ymList to an in-memory JsonArray and then wrap it inside a JsonObject to which you add your dtInfo properties:您可以首先使用Gson.toJsonTree(Object)ymList转换为内存中的JsonArray ,然后将其包装在您添加dtInfo属性的JsonObject中:

JsonObject dtInfoJsonObj = new JsonObject();
dtInfoJsonObj.addProperty​("draw", dtInfo[0]);
dtInfoJsonObj.addProperty​("recordsTotal", dtInfo[1]);
dtInfoJsonObj.addProperty​("recordsFiltered", dtInfo[2]);

Gson gson = new Gson();
JsonArray ymJsonArray = gson.toJsonTree(ymList).getAsJsonArray();
dtInfoJsonObj.add("data", ymJsonArray);

String json = gson.toJson(dtInfoJsonObj);

Wrap data in separate class将数据包装在单独的类中

Alternatively you can create a separate class, eg DtInfo , which contains the properties and the data and then have Gson serialize that.或者,您可以创建一个单独的类,例如DtInfo ,其中包含属性和数据,然后让 Gson 对其进行序列化。 This approach is likely more efficient since there is no intermediate step creating a JsonElement tree.这种方法可能更有效,因为没有创建 JsonElement 树的中间步骤。

class DtInfo {
    // Gson will use the field names during serialization; you can also customize them
    // using `@SerializedName`
    // Additionally you can make the fields private if you want
    public final int draw;
    public final int recordsTotal;
    public final int recordsFiltered;
    public final List<YthMmbrSectDtls> data;

    public DtInfo(int draw, int recordsTotal, int recordsFiltered, List<YthMmbrSectDtls> data) {
        this.draw = draw;
        this.recordsTotal = recordsTotal;
        this.recordsFiltered = recordsFiltered;
        this.data = data;
    }
}

And then create the JSON like this:然后像这样创建 JSON:

DtInfo dtInfoObj = new DtInfo(dtInfo[0], dtInfo[1], dtInfo[2], ymList);
String json = new Gson().toJson(dtInfoObj);

Also note that you can probably increase performance by storing the Gson instance in a static final field.另请注意,您可以通过将Gson实例存储在static final字段中来提高性能。 Gson is thread-safe (see class documentation ) and this way it will cache the type adapters it uses internally for converting the objects to JSON. Gson 是线程安全的(请参阅类文档),这样它将缓存它在内部用于将对象转换为 JSON 的类型适配器。

Additionally Gson provides toJson overloads which accept an Appendable .另外 Gson 提供toJson重载,它接受一个Appendable You could therefore pass the response.getWriter() to these Gson methods which avoids creating the intermediate String representation of the JSON.因此,您可以将response.getWriter()传递给这些 Gson 方法,从而避免创建 JSON 的中间String表示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM