Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
156 views
in Technique[技术] by (71.8m points)

java - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...