Search code examples
jsonstruts2

Struts2 Only Use Specific Variable Object for JSON Result (not all Action variables)


Suppose my Struts mapping returns a JSON string,

    <action name="retrieveJson" method="retrieveJson" class="myapp.WebServiceAction">
        <result type="json">
            <param name="contentType">text/plain</param>
        </result>       
    </action>

My Action class has multiple variables that could be "construed" as the potential result.

public class WebServiceAction {
   private List<PublicationRecord> publicationRecords; // getters+setters
   private List<ReviewRecord> reviewRecords; // getters+setters
   private List<CustomRecord> customRecords; // getters+setters
}

When I do the following, I set the particular variable that I want, but Struts2 seems to return all variables under the Action that are suitable:

public String retrieveJson() {
   publicationRecords = service.getPublicationRecords();
   return SUCCESS;
}

Is it wrong to return SUCCESS? I only want the JSON-ified variable that I set in this method. Right now, it's returning all 3 vars,

{
  "publicationRecords" : ..,
  "reviewRecords" : null,
  "customRecords" : null
}

Expected:

{"publicationRecords" : .. }

Solution

  • For this you could use 2 properties. excludeNullProperties or includeProperties for serializing only the desired fields. Also includeProperties allow the use of regular expressions in case you do not want to serialize the full object content.

    <result type="json">
      <param name="includeProperties">
        ^entries\[\d+\].clientNumber,
        ^entries\[\d+\].scheduleNumber,
        ^entries\[\d+\].createUserId
      </param>
    </result>
    

    Here is the official documentation.