Ronak Joshi Ronak Joshi - 1 year ago 94
jQuery Question

How to get json object using its key value in Struts?

I am working on web services in struts. Now I want json object using its key value. Then I have to post something like array in response. I have no idea how to do that in Struts. I know how to do it in Servlets. So, I am using the following code I have tried, but I think it is different in Struts.

JSONObject json = (JSONObject)new JSONParser().parse(jb.toString());
String key_value= json.get("key").toString();

So, how to do it in Struts. Please also tell me how to parse json array in response.

Answer Source

Working with JSON not necessary to send JSON to Struts. Even if it could be configured to accept JSON content type, it won't help you. You can use ordinary request to Struts with the data passed in it. If it's an Ajax call then you can use something like

   url: "<s:url namespace="/aaa" action="bbb"/>",     
   data : {key: value},
   success: function(json){
     $.each(json, function( index, value ) {
       alert( index + ": " + value );

The value should be an action property populated via params interceptor and OGNL. The json returned in success function should be JSON object and could be used directly without parsing.

You need to provide action configuration and setter for the property key.


<package name="aaa" namespace="/aaa"  extends="json-default">
  <action name="bbb" class="com.bbb.Bbb" method="ccc">
   <result type="json">
     <param name="root">

This configuration is using "json" result type from the package "json-default", and it's available if you use struts2-json-plugin.

Action class:

public class Bbb extends ActionSupport {

  private String key;

  private List<String> value = new ArrayList<>();

  public String ccc(){
    return SUCCESS;

When you return SUCCESS result, Struts will serialize a value property as defined by the root parameter to the JSON result by invoking its getter method during serialization.

If you need to send JSON to Struts action you should read this answer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download