vc/mfc 解析json 字符串教程 作者: juoliii 时间: 2023-05-07 分类: 开发,c++ 经过对比,c++解析json,最好用的还是json11,[https://github.com/dropbox/json11](https://www.oschina.net/action/GoToLink?url=https%3A%2F%2Fgithub.com%2Fdropbox%2Fjson11),这个库是基于c++11标准的 集成方式:下载头文件和cpp文件,复制到工程目录下,在工程上右击添加现有项,引入两个文件即可 ![](https://oscimg.oschina.net/oscnet/up-507a30f89f7c5b98ca3d35d01f032ab928b.png) 例子如下 ``` //JSON对象转json字符串 json11::Json my_json = json11::Json::object{ //json11支持的数据类型 { "keystr","value1" }, { "keybool",false }, { "keyint",5 }, { "keydouble",5.5}, { "keyarr", json11::Json::array { 1, 2, 3,6,7 } }, { "keyobj", json11::Json::object{{"key_obj","key_obj_val"}}}, }; std::string json_str = my_json.dump(); std::cout << "json_str: " << json_str << "\n"; json11::Json json = json11::Json::array{ json11::Json::object { { "key", "val" } } }; std::string str = json[0]["key"].string_value(); std::cout << "str===>>>: " << str << "\n"; //JSON字符串转对象 const std::string simple_test = "{\"k1\":\"v1\", \"k2\":42, \"k3\":[\"a\",123,true,false,null]} "; std::string err; const auto json1 = json11::Json::parse(simple_test, err); std::cout << "k1: " << json1["k1"].string_value() << "\n"; std::cout << "k3: " << json1["k3"].dump() << "\n"; for (auto &k : json1["k3"].array_items()) { std::cout << " - " << k.dump() << "\n"; } ``` 标签: none
评论已关闭