如何在Struts中使用其键值获取json对象? [英] How to get json object using its key value in Struts?

查看:121
本文介绍了如何在Struts中使用其键值获取json对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发struts中的web服务。现在我想要使用其键值的json对象。然后我必须在回复中发布类似数组的内容。我不知道如何在Struts中这样做。我知道如何在Servlets中做到这一点。所以,我使用的是我尝试过的以下代码,但我认为它在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(); 

那么,如何在Struts中做到这一点。还请告诉我如何在响应中解析json数组。

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

推荐答案

使用JSON不必将JSON发送到Struts。即使它可以配置为接受JSON内容类型,它也无济于事。你可以使用普通的Struts请求和传入的数据。如果它是一个Ajax调用,那么你可以使用类似

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 );
     });
   }
}); 






应该是通过 params 拦截器和OGNL填充的动作属性。成功函数中返回的 json 应该是JSON对象,可以直接使用而无需解析。


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.

您需要提供属性的动作配置和设置器 key

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

struts.xml

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>






此配置使用包中的json结果类型json-default,如果使用 struts2-json-plugin


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

动作类:

public class Bbb extends ActionSupport {

  private String key;
  //setter

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

  public String ccc(){
    value.add("Something");
    return SUCCESS;
  }
} 






当您返回 SUCCESS 结果时,Struts将序列化属性,由 root 通过在序列化期间调用其getter方法来获取JSON结果的参数。


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.

如果您需要将JSON发送到Struts操作,请阅读回答。

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

这篇关于如何在Struts中使用其键值获取json对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆