我需要转换和JS对象来查询字符串,这个对象可以包装嵌套对象,如下所示:
var item = {
field1: 100,
field2: 200,
field3: [ 1,2,3 ],
field4: {
field5: 300,
field6: 'Quad',
field7: [ 4,5,6]
}
};
要转换此对象,请使用此功能
var serialize2 = function(obj, prefix) {
var str = [], p;
for (p in obj) {
if (obj.hasOwnProperty(p)) {
var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
str.push((v !== null && typeof v === "object") ?
serialize2(v, k) :
encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
}
return str.join("&");
};
一旦转换,我的查询字符串就像这样
field4中[字段5] = 300&安培; field4中[字段6] =四
而不是
field4.field5 = 300安培; field4.field6 =四
然后我的Java Spring应用程序无法绑定这个子对象
我该如何解决这个问题?
答案 0 :(得分:1)
只需更改转换功能:
var serialize2 = function(obj, prefix) {
var str = [], p;
for (p in obj) {
if (obj.hasOwnProperty(p)) {
var k;
if (Array.isArray(obj)) {
k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
} else {
k = prefix ? prefix + "." + p : p, v = obj[p];
}
str.push((v !== null && typeof v === "object") ?
serialize2(v, k) :
encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
}
return str.join("&");
};
答案 1 :(得分:1)
function generateQueryParam(parameterMap) {
var queryString = '';
var _keys = Object.keys(parameterMap);
_keys.forEach(mapResolver);
function mapResolver(k, i) {
var value = parameterMap[k];
if (i < _keys.length-1) {
queryString += k + '=' + value + '&';
} else {
queryString += k + '=' + value;
}
}
return queryString;
}