如何在json中将一个对象数组发布到Struts2动作中

时间:2013-11-06 23:11:54

标签: arrays json struts2

我正在向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));
    }
});

行动类:

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

我想检索数组数据

“数据”:[{ “字”: “字词1”, “线索”: “clue1”},{ “字”: “单词2”, “线索”: “clue2”}]

另外,我尝试将数组更改为list,如下所示;我仍然得到getData:null

private WCMap[] data;

private List<WCMap> data;
你能帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:4)

这个答案适合未来的googler,就像我一样 -

<强> 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 :(得分:1)

使WCMap可序列化

public class WCMap implments Serializable{
//...
}