英文:
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<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:
{"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);
}
答案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("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, 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<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:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论