Home > Java > javaTutorial > How to Customize Struts2 JSON Plugin Serialization for Specific Objects?

How to Customize Struts2 JSON Plugin Serialization for Specific Objects?

Linda Hamilton
Release: 2024-12-14 03:37:14
Original
219 people have browsed it

How to Customize Struts2 JSON Plugin Serialization for Specific Objects?

Troubleshooting Struts2 JSON Plugin

Struts2 JSON Plugin Functionality

The Struts2 JSON Plugin operates by serializing the entire action into JSON, excluding transient properties and those without getters.

Customizing Serialization with Root Object

To serialize only a specific object, you can leverage the "root" attribute in struts.xml:

<result type="json">
    <param name="root">
        objectToBeSerialized
    </param>
</result>
Copy after login

Solution for Specific Case

Given a data structure with multiple rows represented as "[col1, col2]", you can create:

  • A Value Object: MyRow with fields col1 and col2
  • An Action class with a list of MyRow called "rows"
  • Update the Struts.xml to set the "root" to "rows"

Example Implementation

Value Object (MyRow.java):

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

    // Getters and setters omitted for brevity
}
Copy after login

Action class (PartAction.java):

public class PartAction implements Serializable {
    private List<MyRow> rows;

    public List<MyRow> getRows() { return rows; }

    public String finder() {
        rows = new ArrayList<>();
        // Loop through search results and populate rows
        return Action.SUCCESS;
    }
}
Copy after login

Struts.xml:

<package name="default" namespace="/ajax" extends="json-default">
    <action name="finder" class="action.Part" method="finder">
        <result type="json">
            <param name="root">rows</param>
        </result>
    </action>
</package>
Copy after login

AJAX Callback Function:

var handledata = function(data) {
    $.each(data, function(index) {
        alert(data[index].col1);
        alert(data[index].col2);
    });
}
Copy after login

The above is the detailed content of How to Customize Struts2 JSON Plugin Serialization for Specific Objects?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template