这是我在项目中写的一个Map对象:
let map = new Map(); for (let i = 0; i < type_checked_value.length; i++) { let type_id = type_checked_value[i] map.set('type_' + type_id + '_quantity', $("#type_" + type_id + "_quantity").val()); map.set('type_' + type_id + '_score', $("#type_" + type_id + "_score").val()); }
我天真的觉得JS自带的JSON对象就可以像Java的那些JSON转换组件一样调用即可实现转换【大雾】
let jsonMap = JSON.stringify(map);
用这个方法给后端之后就是一个空括号了,在java这里接受就是这个结果:
{}
然后找到了这个办法,可以实现JS的Map对象转换JSON
// JS map对象转换Json方法 https://blog.csdn.net/Jac__Xu/java/article/details/80969219 function mapToJson(m) { var str = '{'; var i = 1; m.forEach(function (item, key, mapObj) { if(mapObj.size == i){ str += '"'+ key+'":"'+ item + '"'; }else{ str += '"'+ key+'":"'+ item + '",'; } i++; }); str +='}'; //console.log(str); return str; }
传到了后台之后就是这个效果了:
{"type_2_quantity":"2","type_3_score":"5","type_1_score":"4","type_1_quantity":"2","type_3_quantity":"3","type_2_score":"5"}
在Java这里就使用了FastJson来处理转换的:
@Test public void parseJavaScriptMapObject(){ String json = "{"type_2_quantity":"2","type_3_score":"5","type_1_score":"4","type_1_quantity":"2","type_3_quantity":"3","type_2_score":"5"}"; // JSON.parseObject(json); Map map = JSON.parseObject(json); System.out.println(map); Object type_2_quantity = map.get("type_2_quantity"); System.out.println(type_2_quantity); }
测试的结果是能取到值的
{"type_2_quantity":"2","type_3_score":"5","type_1_score":"4","type_1_quantity":"2","type_3_quantity":"3","type_2_score":"5"} 2 Process finished with exit code 0
大概就这样了,没有别的补充