Visual Studio 配置 C++ JsonCpp 使用环境
Yiwei Zhang
·
2022-11-02
·
via 又见苍岚
JSON是一种纯字符串形式的数据,它本身不提供任何方法(函数),非常适合在网络中进行传输,C++ 中操作 JSON 数据主要使用 Jsoncpp 库,本文记录使用方法。
简介
使用配置
下载源码
编译
需要安装 Cmake, VS 环境
- 我们自己编译需要用到的库,这就用到了 CMake 的 Gui 工具
- 运行
cmake-gui 选择源码文件夹和目标文件夹(build2)
- 点击
configure,在弹出的页面中,第一项会默认选择 VS,第二项选择 x64,其它不用选

- 点击
finish
- CMake 准备好后点击
Generate


环境配置


- 附加库目录加入编译生成的
lib/Debug (如果是 Release 就换成 Release) 文件夹


- 此外,还需要告诉系统我们刚刚编译好的
dll 文件位置,可以选择将文件直接放到项目目录中
- 我们的
dll 文件位置在 build/bin/Debug/jsoncpp.dll ,将其拷贝到项目中即可
JsonCpp使用
官方文档有详细的应用,
引入工程
- 在代码中引入
json.h 文件,即可使用 JsonCpp 的功能
读取 Json
- 读 json 文件的思路是:
- 创建
ifstream 对象导入文件字符流
- 建立
Json::Value 对象用于接收 json 信息
- 使用 Json::Reader 对象的
parse 方法将字符流解析到 Value 对象中
- 示例 json 文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| { "version": "4.6.0", "flags": {}, "shapes": [ { "label": "OK", "points": [ [ 560.0, 756.0 ] ], "group_id": null, "shape_type": "point", "flags": {} } ], "imagePath": "29.png", "imageData": null, "imageHeight": 3072, "imageWidth": 4096 }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| #include <json/json.h> #include <io.h> #include <fstream> #include <string> #include <iostream>using namespace std; int main() { Json::Reader reader; Json::Value root; ifstream is; string json_path = "test.json"; is.open(json_path, ios::binary); if (reader.parse(is, root)) { int data = root["shapes"][0]["points"][0][0].asInt(); cout << data << endl; } return 0; }
|
可以通过此代码获取数据 560
写入 Json
- 思路和读取的类似,顺序反过来:
- 构造需要写到磁盘的
Json::Value 对象,加入需要保存的数据
- 用
Json::StyledWriter 将对象导出成字符串
- 将字符串通过
ofstream 写入本地文件
- 示例代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| #include <json/json.h> #include <fstream> #include <string> using namespace std; int main() { Json::Value root; root["test"] = 123; Json::StyledWriter style_writer; string info_str = style_writer.write(root); string info_path = "test.json"; ofstream ofs(info_path); ofs << info_str; ofs.close(); return 0; }
|
参考资料
文章链接:
https://www.zywvvd.com/notes/coding/cpp/jsoncpp/jsoncpp/
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。