C++使用nlohmann json

最好用的c++ json库是 nlohmann
github 地址:https://github.com/nlohmann/json.git

提示

把变量写成json容易,可是把json变成变量就要复杂一点,不过对于nlohmann一点都不复杂

json是什么

不多说了

怎么使用这个库

编译安装

mkdir build
cd build
cmake ..
make
sudo make install

头文件

#include "nlohmann/json.hpp"    //实际位置在 /usr/include中,so和a文件也在默认的地方

写json

对于基本类型,直接赋值,简单粗暴
对于复杂类型,要自定义函数,使用基本类型来实现
#include "nlohmann/json.hpp"
#include <iostream>
#include <fstream>
#include <eigen3/Eigen/Eigen>

using json = nlohmann::json;

using namespace std;
using namespace Eigen;

int main()
{
	nlohmann::json json;
    Eigen::Vector3d o(3,4,5);
    Eigen::Quaterniond origin_(2, 0, 1, -3);
    json["id"] = id;
    json["map_type"] = type_;
    nlohmann::json json_origin_position;
    json_origin_position["x"] = o.x();
    json_origin_position["y"] = o.y();
    json_origin_position["z"] = o.z();
    nlohmann::json json_origin_rotation;
    json_origin_rotation["w"] = origin_.w();
    json_origin_rotation["x"] = origin_.x();
    json_origin_rotation["y"] = origin_.y();
    json_origin_rotation["z"] = origin_.z();
    nlohmann::json json_origin;
    json_origin["position"] = json_origin_position;
    json_origin["rotation"] = json_origin_rotation;
    json["origin"] = json_origin;
    cout << json.dump(2) << std::endl;
    std::ofstream os("test.json");
    os << json.dump(4) << endl;
    return 0;
}

读json

  1. 使用 json["somename"].get<T>(),如 basictype x = json["somename"].get<basictype>();
  2. 使用 json.at("somename").get_to(variable)
  3. 对于自定义的类型,需要序列化你的class或者struct,即加上序列化方法from_json(const json& json, T& var)
struct hl{
    int id;
};
}
hl  m = json["name"].get<hl>(); //错误

需要为struct hl加上序列化方法from_json(const json& json, hl* var)
修改上面的struct hl

struct hl{
    int id;
};

void from_json(const json& j, hl& h){
    j.at("id").get_to(h.id);
}
hl  m = json["name"].get<hl>(); //正确
  1. 对于class定义的类型,可以将上面的 from_json方法改成 friend型,这样就可以访问class的私有变量啦
  • 11
    点赞
  • 47
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值