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

北慕城南 提交于 2019-12-29 08:25:54

问题


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.


回答1:


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

$.ajax({
   url: "<s:url namespace="/aaa" action="bbb"/>",     
   data : {key: value},
   dataType:"json",
   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.

struts.xml:

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

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;
  //setter

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

  public String ccc(){
    value.add("Something");
    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.



来源:https://stackoverflow.com/questions/27141534/how-to-get-json-object-using-its-key-value-in-struts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!