views:

148

answers:

1

I'm using jQuery to post JSON to a Java server, but I think my JSON must be wrong. Here's an example of my data and how I'm sending it:

var lookup = {
    'name': name,
    'description': description,
    'items': [{
        'name': itemName,
        'value': itemValue
    }]
}

$.ajax({
    type: 'post',
    data: lookup,
    dataType: 'json'
});

I'm using Wicket's AbstractAjaxBehavior to receive the data and would like to get a single JSON string that I can parse. When I get a Map of the parameters passed, the keyset looks like this:

items[0][name],
description,
name,
items[0][value],

Obviously I can easily get the values for name and description, but the key for my array of items is messed up. I'm sure it's something simple, but I seem to keep running around the solution. Any suggestions? Thanks!

+5  A: 

You have to use JSON.stringify:

$.ajax({
    type: 'post',
    data: JSON.stringify(lookup),
    contentType: 'application/json',
    dataType: 'json'
});

You should also specify 'application/json' as the contentType. By default jQuery will serialize objects with application/x-www-form-urlencoded (even if the contentType is application/json'). So you have to do it manually.

EDIT: Key for 'post' should be type, not method.

Matthew Flaschen
jQuery automatically adds the content type as application/json when you specify the dataType as json, doesn't it? I did need to stringify my JSON, though, which solved my problem. Thanks for catching that! Also, if you want your data to come back as a parameter value and not a key, send it like this: `data: {'lookup': JSON.stringify(lookup)}`
Jared
@Jared, no. `dataType` specifies what you expect the server to send. `contentType` is the content type *you're* sending, and jQuery will not change it based on dataType. And `{'lookup': JSON.stringify(lookup)}` isn't quite correct. If lookup is `{foo: "bar"}`, that will be url-encoded to something like `lookup=%7B%22foo%22%3A%22bar%22%7D` That obviously isn't a valid JSON document. When you're posting application/json, you don't use url-encoding. I think this might be connected to you putting `method: 'post'`. It should be type: 'post'. Method is ignored, and the default is GET.
Matthew Flaschen
Ah, excellent explanation! Thanks!
Jared
Note: If you get a "JSON is undefined" error (IE6/7) you'll need to include json.org's latest json.js file in your page.
Jared