0

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
  • Not sure, but you could use a POJO for this. A plain class with your list, and dt's specific data inside. Or... is it possible to change Gson by another (json) lib? If it was Google Json Simple, it could be easier, but this is just my opinion. Commented Sep 4, 2020 at 4:09

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Marcono, I will try your additional comments as well. Kind regards, Glyn

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.