The Struts2 JSON Plugin has a unique way of operating. It handles the serialization of actions into JSON, but only for certain elements:
If you prefer to serialize only specific objects, the plugin provides a solution: the "root" attribute. This attribute allows you to specify the root object to be serialized using an OGNL expression.
<result type="json"> <param name="root"> objectToBeSerialized </param> </result>
The Action class should contain the following:
private CustomObject objectToBeSerialized; public CustomObject getObjectToBeSerialized() { return this.objectToBeSerialized; }
CustomObject can represent various data types, such as primitives, strings, arrays, etc.
By utilizing this method, you can return SUCCESS and ERROR like usual AJAX Struts2 actions without compromising framework conventions. Furthermore, you can access the serialized JSON object directly from the AJAX jQuery call's callback function.
Assuming your data structure follows the pattern:
row1 [col1, col2], row2 [col1, col2], rowN [col1, col2]
You could employ the following approach:
public class MyRow implements Serializable { private String col1; private String col2; // Getters }
public class PartAction implements Serializable { private List<MyRow> rows; // Getter public List<MyRow> getRows() { return this.rows; } public String finder() { rows = new ArrayList<MyRow>(); // Populate the list with data } }
<result type="json" > <param name="root"> rows </param> </result>
var handledata = function(data) { $.each(data, function(index) { alert(data[index].col1); alert(data[index].col2); }); }
This approach allows you to serialize your desired data structure, making it accessible within your AJAX callback function.
The above is the detailed content of How Does the Struts2 JSON Plugin Serialize Data Structures for AJAX Calls?. For more information, please follow other related articles on the PHP Chinese website!