vue 传递数组后端java接收问题(qs和json)
一、问题描述1.通过qs.stringify()let array = [{"name":"a","id":1},{"name":"b","id":2},{"name":"c","id":3}]let data = {array : array,numbe...
一、问题描述
1.通过qs.stringify()
let array = [
{"name":"a","id":1},
{"name":"b","id":2},
{"name":"c","id":3}
]
let data = {
array : array,
number : 1,
string : "STRING"
}
this.$axios({
method: "post",
url: "url",
data: qs.stringify(data)
}).then(res => {});
结果:
array[0][name] a
array[0][id] 1
array[1][name] b
array[1][id] 2
array[2][name] c
array[2][id] 3
number 1
string STRING
2.通过JSON.stringify()
this.$axios({
method: "post",
url: "url",
data: JSON.stringify(data)
}).then(res => {});
结果:
{"array":[{"name":"a","id":1},{"name":"b","id":2},{"name":"c","id":3}],"number":1,"string":"STRING"}
如果java接收时使用的是List,那么使用qs来转化数组是会报错的,我测试是在spring mvc自动转配时。
而选择JSON来传化可以解决这个问题,可是JSON转化后端接收可能会出现数据为 [] 和为 0 的结果(原因还在寻找)
二、解决方法
1.将后端接收改为数组
或
2.将数组先用JSON转一次,再加入对象,再用qs来转
结果:
array [{"name":"a","id":1},{"name":"b","id":2},{"name":"c","id":3}]
number 1
string STRING
例如:
let arr = {
"entity.productName": that.ruleForm.message,
entityListString: JSON.stringify(that.productCoreList),
};
console.log("arr", arr);
that.$axios
({
method: "post",
url: "/api/add.do",
data: this.qs.stringify(arr)
})
// .post("/api/add.do",this.qs.stringify(arr))
.then(function (response) {
console.log("成功" + response);
if (response.data.resultFlag == "success") {
}
})
.catch(function (error) {
console.log("失败,,,", error);
});
后台使用String接收 再转成你要的List<T>
public void setProductCoreListString(String productCoreListString) {
this.productCoreListString = productCoreListString;
if (!StringUtils.isEmpty(this.productCoreListString)) {
ObjectMapper mapper = new ObjectMapper();
try {
List<ProductCore> list = mapper.readValue(productCoreListString, new TypeReference<List<ProductCore>>() {
});
productCoreList = list;
} catch (IOException e) {
e.printStackTrace();
log.error("[setProductCoreListString]:"+e,toString());
}
}
}
private String productCoreListString;
更多推荐
所有评论(0)