arrays之如何将 json 中的对象数组发布到 Struts2 操作
mayingbao
阅读:42
2024-10-01 17:34:08
评论:0
我正在向 Struts2 应用程序发送 JSON 请求。 json 请求具有值数组。这是 JSON 请求:
{"row":"10","col":"10","data":[{"word":"word1","clue":"clue1"},{"word":"word2","clue":"clue2"}]}
JQuery 代码:
jasonRequest = createpuzzle_createjson();
$.ajax({
type: 'POST',
url:'create.action',
dataType: 'json',
data: jasonRequest,
success: function(data){
console.log(stringify(data));
}
});
Action 类:
public class GenerateCWAction extends ActionSupport{
private String row;
private String col;
private WCMap[] data;
public String getRow() {
return row;
}
public void setRow(String row) {
this.row = row;
}
public String getCol() {
return col;
}
public void setCol(String col) {
this.col = col;
}
public WCMap[] getData() {
return data;
}
public void setData(WCMap[] data) {
this.data = data;
}
public String execute() {
System.out.println("getRow:" + getRow());
System.out.println("getCol:" + getCol());
System.out.println("getData:" + getData());
return SUCCESS;
}
}
WCMap类:
public class WCMap {
private String word;
private String clue;
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public String getClue() {
return clue;
}
public void setClue(String clue) {
this.clue = clue;
}
输出:
getRow:10
getCol:10
getData:null
我要取回数组数据
"数据":[{"word":"word1","clue":"clue1"},{"word":"word2","clue":"clue2"}]
此外,我尝试将数组更改为如下列表;我还是得到了 getData:null
private WCMap[] data;
到
private List<WCMap> data;
你能帮我解决这个问题吗?
请您参考如下方法:
这个答案是为像我这样的 future 谷歌人准备的 -
<强> 1。创建拦截器堆栈 强>
<interceptors>
<interceptor-stack name="jsonStack">
<interceptor-ref name="json">
<param name="enableSMD">true</param>
</interceptor-ref>
</interceptor-stack>
</interceptors>
<强> 2。将此拦截器用于您的 json 操作 强>
<action name="youraction" class="your class" method="methodName">
<interceptor-ref name="jsonStack"></interceptor-ref>
<result type="json" />
</action>
<强> 3。 Ajax 调用 强>
var ajaxData = {};
ajaxData["array"] = [//your data]; // e.g ["data1","data2"];
$.ajax( {
"dataType": 'json',
"type": "POST",
"url": 'youraction.action',
"data": JSON.stringify(ajaxData),
contentType: "application/json; charset=utf-8",
async : false,
success: function (json) {
console.log('success :'+json);
},
complete: function (msg,a,b) {
console.log('complete :'+msg);
},
error : function(msg,a,b){
console.log('error:'+msg);
}
} );
<强> 4。在您的操作类方法中为数组创建 getter 和 setter 强>
List<String> array = new ArrayList<String>();
public List<String> getArray() {
return array;
}
public void setArray(List<String> array) {
this.array = array;
}
声明
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。