0

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" : .. }
3
  • I think I found the solution, stackoverflow.com/questions/6880276/… it's excludeNullProperties or excludeProperties by name Commented Aug 21, 2018 at 19:37
  • 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? Commented Aug 22, 2018 at 14:27
  • 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. Commented Aug 22, 2018 at 19:59

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.