About Struts2-JSON Plugin
Struts2 JSON Plugin works in a particular way:
The JSON plugin provides a “json” result type that serializes actions into JSON.
It serializes the entire Action into JSON, except
- transient properties
- properties without the Getter
If you don’t want the whole Action to be serialized, but only one object of your choice, you can specify a Root Object:
Use the “root” attribute(OGNL expression) to specify the root object to be serialized.
it can be done in struts.xml
like this:
<result type="json">
<param name="root">
objectToBeSerialized
</param>
</result>
while the Action should have:
private CustomObject objectToBeSerialized;
public CustomObject getObjectToBeSerialized(){
return this.objectToBeSerialized;
}
Where CustomObject can be a Primitive, a String, an Array, etc…
Using it this way (the way it is built for), you can return SUCCESS
and ERROR
like in any other AJAX Struts2 Action, without breaking the framework conventions, and access the serialized JSON object from the callback function of the AJAX jQuery call like any other field (if using rootObject, the “data” of var handledata = function(data)
would be your object, otherwise it would be your Action).
About your specific case
In your case, assuming your object structure looks like this
row1 [col1, col2],
row2 [col1, col2],
rowN [col1, col2]
you could create a List of an object with two columns:
Value Object
public class MyRow implements Serializable {
private static final long serialVersionUID = 1L;
private String col1;
private String col2;
// Getters
public String getCol1(){
return this.col1;
}
public String getCol2(){
return this.col2;
}
}
Action class
public class PartAction implements Serializable {
private static final long serialVersionUID = 1L;
private List<MyRow> rows;
// Getter
public List<MyRow> getRows() {
return this.rows;
}
public String finder() {
String result = Action.SUCCESS;
rows = new ArrayList<MyRow>();
try {
Iterator it = findList.iterator();
while(it.hasNext()) {
SearchResult part = (SearchResult) it.next();
MyRow row = new MyRow();
row.setCol1(part.getcol1());
row.setCol2(part.getcol2());
rows.add(row);
}
} catch (Exception e) {
result = Action.ERROR;
log.error(e);
}
return result;
}
}
Struts.xml
<package name="default" namespace="/ajax" extends="json-default">
<action name="finder" class="action.Part" method="finder" name="finder">
<result type="json" >
<param name="root">
rows
</param>
</result>
</action>
</package>
To test it in the AJAX Callback Function, simply use $.each
:
var handledata = function(data) {
$.each(data, function(index) {
alert(data[index].col1);
alert(data[index].col2);
});
}
Of course you can use a List<List<String>>
instead of a Custom object, or any other object structure you like more than this: it was only to get you the idea.