Gopal
Gopal

Reputation: 1340

How do I control which properties of my data objects are serialized to the JSON response in Struts 2?

I've worked with struts for quite sometime now, but never figured the awesome "json" response type.

I have a large list of objects that I want to return to client. I use only a subset of these fields (typically 'displayName's) on the UI.

Is there a way to restrict the fields that are serialized as JSON back to the client?

One obvious approach I could think of is to create a view object which has subset of the fields. Please suggest the best practice here.

Upvotes: 0

Views: 1068

Answers (2)

Angel Tsvetkov
Angel Tsvetkov

Reputation: 421

In my practice the easiest way I found for playing with JSON objects is GSON. Well documented and intuitive for using. Helped me in many cases.

It is very easy to solve your problem by using GSON.

https://sites.google.com/site/gson/gson-user-guide#TOC-Excluding-Fields-From-Serialization-and-Deserialization

https://sites.google.com/site/gson/gson-user-guide#TOC-Goals-for-Gson

Upvotes: 1

Umesh Awasthi
Umesh Awasthi

Reputation: 23587

You can use exclude property of json plugin to exclude properties which you don't want to serialize.

<interceptor-ref name="json">
  <param name="enableSMD">true</param>
  <param name="excludeProperties">
    login.password,
    studentList.*\.sin
  </param>
</interceptor-ref>

For more details refer to json-plugin

Upvotes: 3

Related Questions