0
votes

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" : .. }
1
I think I found the solution, stackoverflow.com/questions/6880276/… it's excludeNullProperties or excludeProperties by name - gene b.
It's also in the plugin's documentation :/ That's often a good place to start looking for documentation. Unrelated, but why are you setting the response to text/plain instead of indicating it's JSON? - Dave Newton
Thanks; I have another question that maybe you could answer that I scoured the documentation for but couldn't find a clean answer: stackoverflow.com/questions/51974251/… How to customize the resulting JSON in a Struts 2.3.14 app, where we can't define a custom JsonWriter. - gene b.

1 Answers

1
votes

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.