用JS把Java的Map对象转为Json对象

在工作中遇到这么一个问题,在前端JS把后台传来的Map转成Json时出错,不管是用eval()还是用JSON.parse()都报错,最后发现是Map.toString字符串和Json的字符串格式不相同。

public static void main(String [] args){
    Map map = new HashMap();
    map.put(111,"one");
    map.put(222,"two");
    map.put(333,"three");
    System.out.println(map);
}
//{222=two, 111=one, 333=three}
1
2
3
4
5
6
7
8
转换代码如下:

//Java Map对象的String字符串转换为Json
function map2Json(mapStr){
    var subStr = mapStr.substring(1,mapStr.length-1);
    var arr = subStr.split(",");
    var newJson = {};
    for(var i in arr){
        var tmpObj = arr[i].split("=");
        newJson[$.trim(tmpObj[0])] = tmpObj[1];
    }
    return newJson;
}
--------------------- 
作者:Wayss_S 
来源:CSDN 
原文:https://blog.csdn.net/qq1332479771/article/details/79426756 
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用第三方库,比如 RapidJSON 或者 nlohmann/json 来将 map 对象转为 JSON 格式的数据。 以下是使用 RapidJSON 的示例代码: ```c++ #include <iostream> #include "rapidjson/document.h" #include "rapidjson/writer.h" #include "rapidjson/stringbuffer.h" #include <map> using namespace rapidjson; using namespace std; int main() { // 定义一个 map 对象 map<string, int> myMap; myMap["Alice"] = 25; myMap["Bob"] = 30; myMap["Charlie"] = 35; // 创建一个 JSON 对象 Document doc; doc.SetObject(); // 遍历 map 对象,将数据添加到 JSON 中 for (auto& kv : myMap) { Value key(kv.first.c_str(), doc.GetAllocator()); Value val(kv.second); doc.AddMember(key, val, doc.GetAllocator()); } // 将 JSON 对象转为字符串 StringBuffer buffer; Writer<StringBuffer> writer(buffer); doc.Accept(writer); string jsonStr = buffer.GetString(); // 输出 JSON 字符串 cout << jsonStr << endl; return 0; } ``` 输出结果: ``` {"Alice":25,"Bob":30,"Charlie":35} ``` 如果使用 nlohmann/json 库,将会更加简单。示例代码如下: ```c++ #include <iostream> #include <map> #include "json.hpp" using json = nlohmann::json; using namespace std; int main() { // 定义一个 map 对象 map<string, int> myMap; myMap["Alice"] = 25; myMap["Bob"] = 30; myMap["Charlie"] = 35; // 将 map 对象转为 JSON 格式 json j(myMap); // 输出 JSON 字符串 cout << j.dump() << endl; return 0; } ``` 输出结果与上面的示例相同: ``` {"Alice":25,"Bob":30,"Charlie":35} ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值