最好用的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
- 使用
json["somename"].get<T>()
,如basictype x = json["somename"].get<basictype>();
- 使用
json.at("somename").get_to(variable)
- 对于自定义的类型,需要序列化你的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>(); //正确
- 对于class定义的类型,可以将上面的 from_json方法改成 friend型,这样就可以访问class的私有变量啦