详解:https://blog.csdn.net/forrid/article/details/78867679
json for modern c++的使用:https://blog.csdn.net/fengxinlinux/article/details/71037244
JSON for Modern C++ 是德国大牛nlohmann写的:
https://github.com/nlohmann/json#projects-using-json-for-modern-c
特点
- 语法直观,简单易用
- 微型集成,仅有json.hpp,无依赖,符合c++11标准(只需要下载json.hpp即可, https://github.com/nlohmann/json/releases/download/v3.6.1/json.hpp)
- 严格测试,单元测试100%覆盖
- 高效内存
- 高速
基本配置
1.将json.hpp
复制到c++工程文件中
2. 在main.cpp文件中,添加以下代码
#include "json.hpp"
// 为方便起见,设置命名空间
using json = nlohmann::json;
3.编译
对于GCC和Clang编译器,可能出现以下问题:
Q1:C++出现to_string is not a member of std 或者 to_string was not declared in this scope的
A1:对于GCC和Clang编译器,需要打开c++11 支持
以codeblocks为例:
1)点击settings
->complier
,打开global compiler settings
,在compiler flags
中勾选Have g++ follow the C++11 ISO C++ language standard
,点击ok,具体如下:
2)下载 mingw-to-string-gcc47.zip( http://tehsausage.com/mingw-to-string-gcc47.zip)
3)解压文件,将wchar.h
和stdio.h
复制到codeblocks安装路径中的\mingw\include
中,将它们替换掉;将os_defines.h
复制到\mingw\lib\gcc\mingw32\4.x.x\include\c++\mingw32\bits
中即可。
测试
1 使用iostream
#include <iostream>
#include <fstream>
#include "json.hpp"
using namespace std;
using json=nlohmann::json;
int main()
{
json j; //创建json类
cin>>j; //从cin读入json对象
cout<<j; //输出序列化的json
return 0;
}
/*
输入:
{
"pi": 3.141,
"happy": true,
"name": "Niels",
"nothing": null,
"answer": {
"everything": 42
},
"list": [1, 0, 2],
"object": {
"currency": "USD",
"value": 42.99
}
}
输出:
{"answer":{"everything":42},"happy":true,"list":[1,0,2],"name":"Niels","nothing":null,"object":{"currency":"USD","value":42.99},"pi":3.141}
*/
2 使用fstream
json j; //创建json类
std::ifstream i("file.json"); //可以读取txt、json等文件
i>>j;
cout<<j;