Home >Java >javaTutorial >How Does the Struts2 JSON Plugin Serialize Data Structures for AJAX Calls?

How Does the Struts2 JSON Plugin Serialize Data Structures for AJAX Calls?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-10 10:21:16595browse

How Does the Struts2 JSON Plugin Serialize Data Structures for AJAX Calls?

Struts2-JSON Plugin: Understanding Its Functionalities

The Struts2 JSON Plugin has a unique way of operating. It handles the serialization of actions into JSON, but only for certain elements:

  • Non-transient properties
  • Properties with getters

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.

Addressing Your Scenario

Assuming your data structure follows the pattern:

row1 [col1, col2], 
row2 [col1, col2], 
rowN [col1, col2]

You could employ the following approach:

1. Create a List of Custom Objects

public class MyRow implements Serializable {
    private String col1; 
    private String col2;

    // Getters
}

2. Modify the Action Class

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
    }
} 

3. Adjust Struts.xml

<result type="json" >
    <param name="root">
        rows
    </param>
</result>

4. AJAX Callback Function

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn