3

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

我想检索数组数据

"数据":[{"word":"word1","clue":"clue1"},{"word":"word2","clue":"clue2"}]

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

private WCMap[] data;

private List<WCMap> data;

你能帮我解决这个问题吗?

4

2 回答 2

4

这个答案适用于像我这样的未来谷歌人 -

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.阿贾克斯调用

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;
    }
于 2015-07-07T04:58:10.437 回答
1

使 WCMap 可序列化

public class WCMap implments Serializable{
//...
}
于 2013-11-08T06:41:07.970 回答