C++添加nlohmann/json

通过清心醉

C++添加nlohmann/json

首先我们下载nlohmann/json文件包

把include整个目录,复制到当前的项目里(注和cpp同一级)

这会的文件结构应该是

main.cpp
include\
include\nlohmann\json.hpp
include\nlohmann\detail
省略...

接下来我们配置项目的附加目录

打开工程配置属性,选择C/C++,选择常规,在附加目录里添加对应的include目录

注意:比如我的项目文件结构

D:\VisualStudioProjects\debug\include\nlohmann\json.hpp

就需要选择D:\VisualStudioProjects\debug\include,即nlohmann的上一层

还有一个一定要注意实在Debug还是Release哪个模式下。作者就是在Release配置,然后再Debug调试一直错误。。

这样就可以了。然后来个测试的代码,更多的使用可以查看官方的文档。

#include <iostream>
#include "nlohmann/json.hpp";
using namespace std;
using json = nlohmann::json;    // for convenience 

int main()
{
    //方式一:赋值构造
    json j1;
    j1["name"] = "LeBorn Jame";//字符串  
    j1["number"] = 23;         //整数
    j1["man"] = true;          //布尔值
    j1["children"] = { "LeBorn Jr","Bryce Maximus","Zhuri" };//数组
    j1["behavior"]["funny"] = "gigigigigigi";              //对象中元素值
    j1["wife"] = { {"name","Savannah Brinson"},{"man",false} };//对象

    //方式二:直接构造
    json j2 = {
      {"name","LeBorn Jame"},
      {"number",23},
      {"man",true},
      {"children",{"LeBorn Jr","Bryce Maximus","Zhuri"}},
      {"behavior",{{"funny","gigigigigigi"}}},
      {"wife",{{"name","Savannah Brinson"},{"man",false}}}
    };

    cout << "j1: " << j1 << endl;   //输出json对象值
    cout << "j2: " << j2 << endl;   //输出json对象值
    return 0;
}

注意,如果是MFC下,最好是放在文件的最顶部引用,如果再引用了其他头文件之后引用可能会出现异常错误

关于作者

清心醉 administrator

发表评论

请输入验证码: