سؤال

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.

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

Have a look at this: http://jsfiddle.net/flocsy/vuGL9/

You'll see that your pks is actually sent as a string as you want it, when it's not sent as a string (pks2) it'll look different.

PS: look at the network tab in firebug or inspect element, depending on your browser:

pks: '[{"userName":"theoffspring"}]'

pks2[0][userName2]:'hehe'

So probably your server side does some magick...

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top