Issue
I'm using jQuery File-Upload plugin with Struts 2.
In my action I am populating the JSON object "results"
and that's all I want my action to return.
But it is also including the plugin's file
object as well which is an incomplete JSON and causing everything to break on my callbacks.
(Please note that if I don't populate my result
object then it will return a valid JSON "file"
object.
Is there any way I could avoid returning the "file"
JSON response? I just want my action to return only "results"
{
"results": [
{
"ExcelPath": "/usr/test/test.xlsx",
"ExcelName": "test.xlsx",
"TestExcelStatus": "success"
}
]
}
{
"file": {
"absolute": true,
"absoluteFile": null,
"absolutePath": "\/usr\/local\/apache-tomcat-7.0.39\/temp"
},
"path": "\/usr\/local\/apache-tomcat-7.0.39\/temp\/up
My Action
is as below:
org.json.JSONObject resp = new JSONObject();
JSONArray resultsArray = new JSONArray();
resp.put("results",resultsArray);
JSONObject result = new JSONObject();
result.put("TestExcelStatus", "success");
result.put("ExcelName", this.fileFileName);
result.put("ExcelPath", fileToCreate.getPath());
resultsArray.put(result);
servletResponse.reset();
servletResponse.setHeader("Content-Type","application/json; charset=UTF-8");
servletResponse.setHeader("CacheControl","no-cache");
servletResponse.setHeader("Pragma","no-cache");
servletResponse.setHeader("Expires","-1");
//resp.writeJSONString(out);
resp.write(servletResponse.getWriter());
I am expecting the below line to clear the existing JSON and only return my "results"
JSON. But it is still returning every thing.
servletResponse.reset();
And the desired JSON response must be as below without a "file"
.
{
"results": [
{
"ExcelPath": "/usr/test/test.xlsx",
"ExcelName": "test.xlsx",
"TestExcelStatus": "success"
}
]
}
Solution
The Struts action is always returning a result code that is used by the action invocation to execute a result configured to this action. I suspect that result is of type json
.
If the action returning json
result then by default the root
property is initialized to the action instance or a model if you are using model-driven action.
It means that all public properties of the root
object will be serialized to JSON. You can control this process with annotations placed on the properties, or configure the result with parameters to include/exclude some properties from the result.
Actually you only need to configure the root
parameter of the result to return an object that you serialize to JSON. But because you are writing to response directly you can change the result code returned by the action to NONE
. This is used by the actions that don't return any result.
Answered By - Roman C
Answer Checked By - Mary Flores (JavaFixing Volunteer)