[C++]使用json库生成与解析json

由于要使用json,在github上找到一个方便使用的json库。
https://github.com/nlohmann/json

  1. 使用方法
    使用的时候,仅仅需要将 一个json.hpp 文件包含即可
  2. 文件地址
    为json项目目录下src/json.hpp
#include <iostream>
#include <fstream>
#include "json.hpp"
using json = nlohmann::json;
using namespace std;

int main()
{
    json myjs;      //构建json对象
    //创建json key/value
    myjs["id"] = "F100235";
    myjs["weight"] = 126.63;
    myjs["happy"] = true;
    myjs["userip"] = "192.168.1.1";

    //输出序列化的json值
    cout << myjs << "\r\n";

    //将json保存成文件
    std::ofstream myfile("myjson.json");
    myfile << std::setw(4) << myjs << std::endl;



    system("pause");
    return 0;
}

序列化输出结果

这里写图片描述

生成的json文件

这里写图片描述

猜你喜欢

转载自blog.csdn.net/starelegant/article/details/78213858