我正在使用 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 );
});
}
});
value
应该是通过 params
拦截器和 OGNL 填充的操作属性.success函数中返回的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
提供动作配置和setter.
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>
这个配置使用 "json-default"
包中的 "json"
结果类型,如果你使用 JSON 插件.
This configuration is using "json"
result type from the package "json-default"
, and it's available if you use 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 将通过调用其 getter 将 root
参数定义的 value
属性序列化为 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 操作,您应该阅读 this 答案.
If you need to send JSON to Struts action you should read this answer.
这篇关于如何使用 Struts 中的键值获取 json 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!