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:
我正在使用jQuery向Java服务器发布JSON,但我认为我的JSON一定是错的。这是我的数据的一个例子,以及我如何发送它:
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:
我正在使用Wicket的AbstractAjaxBehavior接收数据,并希望获得一个可以解析的JSON字符串。当我得到传递的参数的映射时,keyset看起来是这样的:
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!
显然,我可以很容易地获得名称和描述的值,但是我的项目数组的键是混乱的。我相信这很简单,但我似乎一直在寻找解决方案。有什么建议吗?谢谢!
1 个解决方案
#1
45
You have to use JSON.stringify:
你必须使用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.
您还应该将“application/json”指定为contentType。默认情况下,jQuery将使用application/x-www-form- urlencoding(即使内容类型是application/json)序列化对象。所以你必须手动操作。
EDIT: Key for 'post' should be type, not method.
编辑:“post”的键应该是类型,而不是方法。
#1
45
You have to use JSON.stringify:
你必须使用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.
您还应该将“application/json”指定为contentType。默认情况下,jQuery将使用application/x-www-form- urlencoding(即使内容类型是application/json)序列化对象。所以你必须手动操作。
EDIT: Key for 'post' should be type, not method.
编辑:“post”的键应该是类型,而不是方法。