Search code examples
javagsonwebwork

json string can't be posted as plain string through jquery ajax?


I want to post a json string as plain string to a action ,then convert the string to List using gson, but the string is still treated as json object by jquery/webwork, I'm using jquery 1.43+webwork+gson, no jquery json plugin or something.

here is action:

public class ImageAction extends BaseAction {

    private String pks;

    public void setPks(String pks) {
        this.pks = pks;
        Gson gson=new Gson();
        List<Map> list=gson.fromJson(pks,new TypeToken<List<Map<String,String>>>(){}.getType());
        System.out.println(list.size());
    }

    ......
}

jquery code:

j$.ajax({
            url:approveUrl,
            data: {pks:'[{"userName":"theoffspring"}]'},
//            dataType:'json',
            type:'post',
//            traditional: true,
            success:function (response) {
                hideProgressBar(parent.document)
                if (response.result==false){
                    alert(response.msg);
                    return;
                }

//                document.location.reload();
            }

        })

I want pks posted as a common string instead of json object. But setPks method turns out not to be invoked when I invoke the jquery code. So strange.


Solution

  • you have'nt serialized the data you are sending through ajax.serialize it at client using JSON.stringify() and send it will be converted to a single string.

    modify your code to:

    $.ajax({
                url:approveUrl,
                data:JSON.stringify(yourdata),
    //            dataType:'json',
                type:'post',
    //            traditional: true,
                success:function (response) {
                    hideProgressBar(parent.document)
                    if (response.result==false){
                        alert(response.msg);
                        return;
                    }
    
    //                document.location.reload();
                }
    
            })
    

    this might work.