如何从服务器端的Java代码正确返回JSON给DataTables?

huangapple go评论74阅读模式
英文:

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

问题

以下是翻译好的内容:

// 合并两个数组并将结果作为 JSON 返回给 DataTables

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

ymList = MySQLConnection.getYouthMmbrAllDtls(archived);

// 测试部分将被替换为数据库调用,如上所示
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);
}

请注意,代码中的注释部分没有被翻译。如果您有任何进一步的问题或需要其他帮助,请随时提问。

英文:

How do I concatenate two arrays and then return the result as JSON to 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. Currently the array returned is:

List&lt;YthMmbrSectDtls&gt; ymList;

Example data is:

[{&quot;youthMemberID&quot;:&quot;MTQ5&quot;,&quot;surname&quot;:&quot;Tendon&quot;,&quot;firstName&quot;:&quot;Achilles&quot;}]

With the DataTables server-side I need to include extra information at the start of the returned JSON such as:

{&quot;draw&quot;:9, &quot;recordsTotal:57&quot;, &quot;recordsFiltered:57&quot;[...]}

So that I return:

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

At least that is my understanding from reading the manuals and watching the videos.

My current code is:

List&lt;YthMmbrSectDtls&gt; ymList;
String[] dtInfo = {&quot;draw&quot;, &quot;recordsTotal&quot;, &quot;recordsFiltered&quot;};

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

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

答案1

得分: 1

有多种不同的方法可以解决这个问题:

修改 JsonElement 树

您可以首先使用 Gson.toJsonTree(Object)ymList 转换为内存中的 JsonArray,然后将其包装在一个 JsonObject 中,向其中添加您的 dtInfo 属性:

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);

在单独的类中包装数据

或者,您可以创建一个单独的类,例如 DtInfo,其中包含属性和数据,然后让 Gson 进行序列化。这种方法可能更高效,因为没有创建 JsonElement 树的中间步骤。

class DtInfo {
    // Gson 在序列化过程中将使用字段名称;您还可以使用 `@SerializedName` 自定义它们
    // 此外,如果需要,您可以将字段设为私有的
    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;
    }
}

然后可以这样创建 JSON:

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

另外还注意到,通过在 static final 字段中存储 Gson 实例,可能可以提高性能。Gson 是线程安全的(请参阅类文档),这样它将缓存内部用于将对象转换为 JSON 的类型适配器。

此外,Gson 提供了接受 Appendable 参数的 toJson 重载版本。因此,您可以将 response.getWriter() 传递给这些 Gson 方法,从而避免创建中间的 JSON 字符串表示。

英文:

There are multiple different ways this can be solved:

Modify JsonElement tree

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:

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

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

String json = gson.toJson(dtInfoJsonObj);

Wrap data in separate class

Alternatively you can create a separate class, e.g. DtInfo, which contains the properties and the data and then have Gson serialize that. This approach is likely more efficient since there is no intermediate step creating a JsonElement tree.

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&lt;YthMmbrSectDtls&gt; data;

    public DtInfo(int draw, int recordsTotal, int recordsFiltered, List&lt;YthMmbrSectDtls&gt; data) {
        this.draw = draw;
        this.recordsTotal = recordsTotal;
        this.recordsFiltered = recordsFiltered;
        this.data = data;
    }
}

And then create the JSON like this:

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 is thread-safe (see class documentation) and this way it will cache the type adapters it uses internally for converting the objects to JSON.

Additionally Gson provides toJson overloads which accept an Appendable. You could therefore pass the response.getWriter() to these Gson methods which avoids creating the intermediate String representation of the JSON.

huangapple
  • 本文由 发表于 2020年9月4日 09:59:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/63733799.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定