6

I have following implementation

public abstract class BaseAcion extends ActionSupport {
    private String result;
    private String message;

    //getters, setters
}

public class MyAction extends BaseAction {
    private String myFirstField;
    private String mySecondField;

    public String execute() {
         ...
         myFirstField = "someValue";
         mySecondField = "someOtherValue";
         ...
         result = SUCCESS;
         message = "Some message here";
         ...
         return result;
    }

    //methods, getters, setters
}

I have used struts2-json plugin, action mapping is

<package name="my-package" namespace="/" extends="json-default" >
    <action name="myAction" class="MyAction">
        <result type="json"></result>
    </action> 
</package>

The response that I receive is something like this.

{
    "myFirstField":"someValue",
    "mySecondField":"someOtherValue"
}

I want to get "result" and "message" fields in response as well.

How can I include BaseAction fields in json response?

1 Answer 1

13

By default properties defined on base classes of the "root" object won't be serialized, to serialize properties in all base classes (up to Object) set "ignoreHierarchy" to false in the JSON result:

Something like

<result type="json">
  <param name="ignoreHierarchy">false</param>
</result>

For details refer to the JSON plugin documentation

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

4 Comments

thank you. But It will serialize all properties of parent. I just want two property of parent in json. I guess I have to use "excludeProperties" in each action mapping. Is there any cleaner way ?
yes that's the way to exclude them else create an inner class within your Action that contains just the information you want to include in the JSON and set it as the base/root object to marshal.
Instead of creating inner class in each action, I think it's better to extend JSON Result Type in my own way. I am going to dive into json plugin. Thanks Umesh for your valuable solution and ideas.
You can even create an inner class in your base action and use that as root object or can use reg expression for including/excluding properties

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.