Search code examples
jqueryajaxjsonjax-wsprototypejs

INVALID JSON FORMAT JQUERY


Hi guys. I get a problem, when i try to make ajax to my JAX-WS service( i use google jsonwebservice library). So on my page i have this code:

function submit(){
         var JSONObject= '{sayHello:{name:"alexei"}}';
         console.log(JSONObject);
            $.ajax({
                type: 'POST',
                url:  '/jaxwsExample-1.0.0-SNAPSHOT/json/hello',
                contentType: 'application/json',
                data: JSON.stringify(JSONObject),
                dataType: 'application/json',
                async: true,
                success: function(data) {
                    console.log("DATA " + data);
                }
            });
     }

And console.log(JSONObject); returns to me:

{sayHello:{name:"alexei"}} 

But when in my TomCat server i got this error:

Caused by: com.jaxws.json.codec.JSONFault: Invalid JSON input : "{sayHello:{name:\"alexei\"}}"

But also i got working example from http://code.google.com/p/jsonwebservice/wiki/GettingStarted

In that example used prototype.js framework which made an ajax call:

 function submit(){
            new Ajax.Request('/jaxwsExample-1.0.0-SNAPSHOT/json/hello', {
                method: 'post',
                contentType: 'application/json',
                postBody: '{"sayHello":{"name":"'+$('name').value+'"}}',
                onSuccess: function(transport) {
                    $('response').update(transport.responseText).setStyle({ background: '#FFFFAA' });
                    $('notice').update(transport.responseText.evalJSON().message).setStyle({ background: '#dfd' });
                }
            });
        }

But i want to use jquery instead of prototype.js, can you help me whats wrong with my jquery ajax call or with JSON object?


Solution

  • Your "object" is actually a string.

    var JSONObject= '{sayHello:{name:"alexei"}}';
    

    So when you later call JSON.stringify the quotes get escaped. Either start with an actual object,

    var JSONObject = {sayHello:{name:"alexei"}};
    

    ...or don't attempt to stringify a string.